-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
62 lines (49 loc) · 1.59 KB
/
script.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
const apiURL = "https://api.lyrics.ovh";
async function searchSongs(term) {
const res = await fetch(`${apiURL}/suggest/${term}`);
const data = await res.json();
showData(data);
}
const result = document.getElementById("result");
function showData(data) {
result.innerHTML = `
<ul class="songs">
${data.data
.map(
(song) =>
`<li>
<button class="btn" data-artist="${song.artist.name}" data-songtitle="${song.title}">${song.artist.name} - ${song.title}</button>
</li>`
)
.join("")}
</ul>
`;
}
async function getLyrics(artist, songTitle) {
const res = await fetch(`${apiURL}/v1/${artist}/${songTitle}`);
const data = await res.json();
if (data.error) {
result.innerHTML = data.error;
} else {
const lyrics = data.lyrics.replace(/(\r\n|\r|\n)/g, "<br>");
result.innerHTML = `
<h2><strong>${artist}</strong> - ${songTitle}</h2>
<span>${lyrics}</span>
`;
}
}
const form = document.getElementById("form");
const search = document.getElementById("search");
form.addEventListener("submit", (e) => {
e.preventDefault();
const searchTerm = search.value.trim();
searchTerm ? searchSongs(searchTerm) : alert("Please type in a search term");
});
result.addEventListener("click", (e) => {
const clickedEl = e.target;
if (clickedEl.tagName === "BUTTON") {
const artist = clickedEl.getAttribute("data-artist");
const songTitle = clickedEl.getAttribute("data-songtitle");
getLyrics(artist, songTitle);
}
});