-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
86 lines (77 loc) · 2.54 KB
/
app.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
const searchSongs = async() => {
const searchText = document.getElementById('search-field').value;
const url = `https://api.lyrics.ovh/suggest/${searchText}`
displaySpinner()
document.getElementById('notification').innerText = ""
//load data
try {
const response = await fetch(url)
const data = await response.json()
if (data.total == 0) {
checkError()
} else {
displaySongs(data.data)
}
} catch (error) {
checkError()
}
}
const checkError = () => {
displaySpinner()
const message = document.getElementById('notification')
message.innerText = "Sorry, we are unable to find that."
}
const displaySongs = songs => {
displaySpinner()
document.getElementById('notification').innerText = ""
const songContainer = document.getElementById('song-container')
songContainer.innerHTML = '';
songs.forEach(song => {
const songDiv = document.createElement('div');
songDiv.className = 'single-result row align-items-center my-3 p-3'
songDiv.innerHTML = `
<div class="col-md-9">
<h3 class="lyrics-name">${song.title}</h3>
<p class="author lead">Album by <span>${song.artist.name}</span></p>
<audio controls>
<source src="${song.preview}" type="audio/mpeg">
</audio>
</div>
<div class="col-md-3 text-md-right text-center">
<button onclick="getLyric('${song.artist.name}','${song.title}')" class="btn btn-success">Get Lyrics</button>
</div>
`;
songContainer.appendChild(songDiv)
})
}
const getLyric = async(artist, title) => {
const url = `https://api.lyrics.ovh/v1/${artist}/${title}`;
displaySpinner()
document.getElementById('notification').innerText = ""
try {
const response = await fetch(url)
const data = await response.json()
if (data.lyrics == "") {
checkError()
} else {
displayLyrics(data.lyrics)
}
} catch (error) {
checkError()
}
}
const displayLyrics = lyrics => {
displaySpinner()
const lyricsDiv = document.getElementById('song-lyrics')
lyricsDiv.innerText = lyrics;
}
const displaySpinner = () => {
const spinner = document.getElementById('loading-spinner')
spinner.classList.toggle('d-none')
}
document.getElementById("search-field").addEventListener("keydown", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
searchSongs()
}
});