-
-
Notifications
You must be signed in to change notification settings - Fork 679
Expand file tree
/
Copy pathscript.js
More file actions
70 lines (63 loc) · 1.83 KB
/
script.js
File metadata and controls
70 lines (63 loc) · 1.83 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
const form = document.getElementById("form");
const search = document.getElementById("search");
const result = document.getElementById("result");
let lastSearchResults = [];
const apiURL = "https://lrclib.net/api";
async function searchSongs(term) {
const res = await fetch(`${apiURL}/search?q=${encodeURIComponent(term)}`);
const data = await res.json();
lastSearchResults = data || [];
showData(lastSearchResults);
}
function showLyricsByIndex(index) {
const song = lastSearchResults[index];
if (!song) {
showAlert("Lyrics not found.");
return;
}
const lyrics = song.plainLyrics || "No lyrics available.";
result.innerHTML = `
<h2><strong>${song.artistName}</strong> - ${song.trackName}</h2>
<span>${lyrics.replace(/(\r\n|\r|\n)/g, "<br>")}</span>
`;
}
function showData(data) {
result.innerHTML = `
<ul class="songs">
${data
.map(
(song, index) => `<li>
<span><strong>${song.artistName}</strong> - ${song.trackName}</span>
<button class="btn" data-index="${index}">Get Lyrics</button>
</li>`
)
.join("")}
</ul>
`;
}
function showAlert(message) {
const notif = document.createElement("div");
notif.classList.add("toast");
notif.innerText = message;
document.body.appendChild(notif);
setTimeout(() => notif.remove(), 3000);
}
// Event Listeners
form.addEventListener("submit", (e) => {
e.preventDefault();
const searchTerm = search.value.trim();
if (!searchTerm) showAlert("Please type in a search term");
else searchSongs(searchTerm);
});
result.addEventListener("click", (e) => {
const clickedElement = e.target;
if (
clickedElement.tagName === "BUTTON" &&
clickedElement.hasAttribute("data-index")
) {
const index = clickedElement.getAttribute("data-index");
showLyricsByIndex(index);
}
});
// Init
searchSongs("one");