-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
90 lines (71 loc) · 2.42 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const form = document.querySelector('#form');
const search = document.querySelector('#search');
const result = document.querySelector('#result');
const more = document.querySelector('#more');
const apiUrl = 'https://api.lyrics.ovh/';
//Function to search by song or artisit
async function searchSongs(term){
const res = await fetch(`${apiUrl}/suggest/${term}`);
const data = await res.json();
showData(data);
}
//Function to update song and artist on the DOM
function showData(data){
result.innerHTML = `
<ul class="songs">
${data.data.map(song => `
<li>
<span><strong>${song.artist.name}</strong> - ${song.title}</span>
<button data-artist="${song.artist.name}" data-songtitle="${song.title}">Get Lyrics</button>
</li>`).join('')
}
</ul>
`;
if (data.prev || data.next) {
more.innerHTML = `
${data.prev ? `<button onclick="getMoreSongs('${data.prev}')">Prev</button>` : ``}
${data.next ? `<button onclick="getMoreSongs('${data.next}')">Next</button>` : ``}
`;
} else {
more.innerHTML = ``;
}
}
//Function to get more songs on the next page or previous
async function getMoreSongs(url){
const res = await fetch(`https://cors-anywhere.herokuapp.com/${url}`);
const data = await res.json();
showData(data);
}
//Function to fetch lyrics
const getLyrics = async function(artist, songTitle){
const res = await fetch(`${apiUrl}/v1/${artist}/${songTitle}`);
const data = await res.json();
//return a new line
//global flag g to check the entire thing
const lyrics = data.lyrics.replace(/(\r\n|\n)/g, '<br>');
result.innerHTML = `
<h2><strong>${artist}</strong> - ${songTitle}</h2>
<span>${lyrics}</span>
`;
more.innerHTML = '';
}
//Event listener for submitting search
form.addEventListener('submit', e => {
e.preventDefault();
const searchTerm = search.value.trim();
if (!searchTerm) {
alert('Please type in something in the search bar');
} else {
searchSongs(searchTerm);
}
});
//Functionality for getting lyrics on button click
//Event delegation
result.addEventListener('click', e => {
var clickedEl = e.target;
if (clickedEl.tagName === 'BUTTON') {
const artist = clickedEl.getAttribute('data-artist');
const songTitle = clickedEl.getAttribute('data-songtitle');
getLyrics(artist, songTitle);
}
});