-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
73 lines (54 loc) · 2.24 KB
/
main.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
// wait for DOM to load before running JS
$(function() {
// form to search spotify API
var $spotifySearch = $('#spotify-search');
// input field for track (song)
var $track = $('#track');
// element to hold results from spotify API
var $results = $('#results');
// loading gif
var $loading = $('#loading');
// submit form to search spotify API
$spotifySearch.on('submit', function (event) {
event.preventDefault();
// empty previous results and show loading gif
$results.empty();
$loading.show();
// save form data to variable
var searchTrack = $track.val();
// spotify search URL
var searchUrl = 'https://api.spotify.com/v1/search?type=track&q=' + searchTrack;
// use AJAX to call spotify API
$.get(searchUrl, function (data) {
// track results are in an array called `items`
// which is nested in the `tracks` object
var trackResults = data.tracks.items;
console.log(trackResults);
// hide loading gif
$loading.hide();
// only append results if there are any
if (trackResults.length > 0) {
// iterate through results
trackResults.forEach(function (result, index) {
// build object of data we want in our view
var trackData = {
albumArt: result.album.images.length > 0 ? result.album.images[0].url : null,
artist: result.artists[0].name,
name: result.name,
previewUrl: result.preview_url
};
// use data to construct HTML we want to show
var $trackHtml = '<div class="row"><div class="col-xs-4"><img src="' + trackData.albumArt + '" class="img-responsive"></div><div class="col-xs-8"><p><strong>' + trackData.name + '</strong> by ' + trackData.artist + '</p><p><a href="' + trackData.previewUrl + '" target="_blank" class="btn btn-sm btn-default">Preview <span class="glyphicon glyphicon-play"></span></a></p></div></div><hr>';
// append HTML to the view
$results.append($trackHtml);
});
// else let user know there are no results
} else {
$results.append('<p class="text-center">No results</p>');
}
});
// reset the form
$spotifySearch[0].reset();
$track.focus();
});
});