-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
97 lines (79 loc) · 2.39 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
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
91
92
93
94
95
96
97
const form = document.getElementById('form');
const search = document.getElementById('search');
const result = document.getElementById('result');
const more = document.getElementById('more');
const apiURL = 'https://api.lyrics.ovh';
const date = new Date();
const year = date.getFullYear;
// Search by song or artist
async function searchSongs(term) {
const res = await fetch(`${apiURL}/suggest/${term}`);
const data = await res.json();
showData(data);
}
// Show song and artist in DOM
function showData(data) {
result.innerHTML = `
<strong class="searchresult">Search Results</strong>
<ul class="songs">
${data.data
.map(
(song,index) => `<li>
<span><strong>${index+1}. ${song.artist.name}</strong> - ${song.title}</span>
<button class="btn" 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 class="morebtn" onclick="getMoreSongs('${data.prev}')">Prev</button>`
: ''
}
${
data.next
? `<button class="morebtn" onclick="getMoreSongs('${data.next}')">Next</button>`
: ''
}
`;
} else {
more.innerHTML = '';
}
}
// Get prev and next songs
async function getMoreSongs(url) {
const res = await fetch(`https://cors-anywhere.herokuapp.com/${url}`);
const data = await res.json();
showData(data);
}
// 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 = `<h2 class="searchresult"><strong >${artist}</strong> - ${songTitle}</h2>
<span class="lyrics">${lyrics}</span>`;
more.innerHTML = '';
}
// Event listeners
form.addEventListener('submit', e => {
e.preventDefault();
const searchTerm = search.value.trim();
if (!searchTerm) {
alert('Please type in a search term');
} else {
searchSongs(searchTerm);
}
});
// Get lyrics button click
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);
}
});