-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
78 lines (63 loc) · 1.86 KB
/
script.js
File metadata and controls
78 lines (63 loc) · 1.86 KB
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
const form = document.getElementById("form");
const search = document.getElementById("search");
const result = document.getElementById("result");
// Api url
const apiURL = "https://api.lyrics.ovh";
// Listen event in form input
form.addEventListener("submit", (e) => {
e.preventDefault();
searchValue = search.value.trim();
if (!searchValue) {
alert("There is nothing to search!");
} else {
searchSong(searchValue);
}
});
// Search song
async function searchSong(searchValue) {
const searchResult = await fetch(`${apiURL}/suggest/${searchValue}`);
const data = await searchResult.json();
showData(data);
}
// Display final result
function showData(data) {
result.innerHTML = `
<ul class="song-list">
${data.data
.map(
(song) => `
<li>
<div>
<img src="${song.artist.picture}" alt="${song.artist.name}" />
<strong>${song.artist.name}</strong>
</div>
<span data-artist= "${song.artist.name}" data-songtitle ="${song.title}">Get lyrics</span>
</li>
`
)
.join(``)}
</ul>
`;
}
// Event listener for get lyrics button
result.addEventListener("click", (e) => {
const clickElement = e.target;
// Checking clicking element is button or not
if (clickElement.tagName === "SPAN") {
const artist = clickElement.getAttribute("data-artist");
const songTitle = clickElement.getAttribute("data-songtitle");
getLyrics(artist, songTitle);
}
});
// Get lyrics for song
async function getLyrics(artist, songTitle) {
const res = await fetch(`${apiURL}/v1/${artist}/${songTitle}`);
const data = await res.json();
const lyrics = data.lyrics.replace(/(\r\n|\r|\n)/g, "<br>");
result.innerHTML = `
<div class="full-lyrics">
<h2>${artist} - ${songTitle}</h2>
<p>${lyrics}</p>
</div>
`;
}