-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
103 lines (87 loc) · 3.32 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
98
99
100
101
102
103
(function() {
Handlebars.templates = Handlebars.templates || {};
var templates = document.querySelectorAll(
'script[type="text/x-handlebars-template"]'
);
Array.prototype.slice.call(templates).forEach(function(script) {
Handlebars.templates[script.id] = Handlebars.compile(script.innerHTML);
});
var myHtml;
var myOtherHtml;
var nextUrl;
var timeout;
$(".submit-btn").on("click", function() {
var userInput = $('input[name="user-input"]').val();
var dropdownInput = $(".artist-or-album").val();
var baseUrl = "https://elegant-croissant.glitch.me/spotify";
myHtml = "";
nextUrl = undefined;
apiRequest(userInput, dropdownInput, baseUrl);
});
$(".more").on("click", function() {
var userInput = $('input[name="user-input"]').val();
var dropdownInput = $(".artist-or-album").val();
apiRequest(userInput, dropdownInput, nextUrl);
});
function apiRequest(input, selection, url) {
$.ajax({
url: url,
data: {
query: input,
type: selection
},
success: function(payload) {
console.log("payload:", payload);
payload = payload.artists || payload.albums;
payload.input = input;
// no results or less than 20
if (payload.items.length < 20) {
$(".more").css({
visibility: "hidden"
});
}
//check if infinite scroll is included in url
if (payload.next != null) {
nextUrl = payload.next.replace(
"https://api.spotify.com/v1/search",
"https://elegant-croissant.glitch.me/spotify"
);
}
loadResults(payload);
if (
location.search.indexOf("scroll=infinite") >= 0 &&
payload.items.length > 0
) {
checkScrollPosition();
} else if (payload.items.length > 0 && payload.next != null) {
$(".more").css({
visibility: "visible"
});
}
}
});
}
function checkScrollPosition() {
var windowHeight = $(window).height();
var pageHeight = $(document).height();
var scrollTop = $(document).scrollTop();
var hasReachedBottom = scrollTop + windowHeight >= pageHeight - 200;
if (hasReachedBottom) {
// get more results!
clearTimeout(timeout);
console.log("TIME TO GET MORE RESULTS!!");
var userInput = $('input[name="user-input"]').val();
var dropdownInput = $(".artist-or-album").val();
apiRequest(userInput, dropdownInput, nextUrl);
} else {
console.log("did not reach bottom yet....");
timeout = setTimeout(checkScrollPosition, 300);
}
}
function loadResults(payload) {
myHtml += Handlebars.templates.results(payload);
myOtherHtml = Handlebars.templates.resultsOrNot(payload);
$(".results-container").html(myHtml);
$(".resultsOrNot").html(myOtherHtml);
}
})();