-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsample.js
63 lines (59 loc) · 2.15 KB
/
sample.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
window.onload = function() {
var results = document.getElementById("content");
var sampleForm = document.getElementById("sample-form");
var query = document.getElementById("query");
var playingClass = 'playing';
var audioObject = null;
function fetchTracks (albumId, callback) {
$.ajax({
url: 'https://api.spotify.com/v1/albums/' + albumId,
}).done(function(response) { callback(response); });
}
function searchAlbums (query) {
$.ajax({
url: 'https://api.spotify.com/v1/search',
data: {
q: query,
type: 'album'
}
}).done(function (response) {
results.innerHTML = '';
var albumsArr = response.albums.items;
albumsArr.forEach(function(obj) {
results.innerHTML +=
`
<div style="background-image:url(${obj.images[0].url})" data-album-id="${obj.id}" class="cover"></div>
`
})
})
}
results.addEventListener('click', function (e){
var target = e.target;
if (target !== null && target.classList.contains('cover')) {
if (target.classList.contains(playingClass)) {
audioObject.pause();
}
else {
if (audioObject) {
audioObject.pause();
}
fetchTracks(target.getAttribute('data-album-id'), function(d){
audioObject = new Audio(d.tracks.items[0].preview_url);
audioObject.play();
target.classList.add(playingClass);
audioObject.addEventListener('ended', function() {
target.classList.remove(playingClass);
});
audioObject.addEventListener('pause', function() {
target.classList.remove(playingClass);
});
});
}
}
});
sampleForm.addEventListener('submit',
function (e) {
e.preventDefault()
searchAlbums(query.value);
}, false)
}