/
index.js
72 lines (68 loc) · 1.75 KB
/
index.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
(function() {
var Ajax = {
get: function(url, cb) {
var x = new XMLHttpRequest();
x.open('GET', url, true);
x.addEventListener('readystatechange', function() {
if (4 == x.readyState) {
if (200 == x.status) {
cb(x.responseText)
}
}
});
x.send();
}
},
VM = {
query: document.querySelector('[name=q]'),
results: document.querySelector('#results'),
audio: document.querySelector('audio'),
apiKey: document.querySelector('[name=apikey]'),
timer: null,
initial: 'Bob',
url: 'https://api.jamendo.com/v3.0/tracks?audioformat=ogg&namesearch=',
ajcb: function(data) {
var obj = JSON.parse(data),
result = '';
for (i in obj.results) {
var res = obj.results[i];
result += '<tr><td>'+
'<a href="#" data-audio="'+
res['audio'] +
'" onclick="VM.play(this);">' +
res['name'] +
'</a></td><td>' +
res['album_name'] +
'</td><td>' +
res['artist_name']+'</td></tr>';
}
this.results.innerHTML = result;
},
search: function(whatfor) {
Ajax.get(
this.url + whatfor + '&client_id='+this.apiKey.value,
this.ajcb.bind(this)
);
},
keyup: function() {
clearTimeout(this.timer);
if (2 < this.query.value.length) {
this.timer = setTimeout(function() {
this.search(this.query.value);
}.bind(this), 400);
}
},
play: function(what) {
this.audio.src = what.getAttribute('data-audio');
this.audio.play();
},
init: function() {
this.query.value = this.initial;
this.query.addEventListener('keyup', this.keyup.bind(this));
this.apiKey.addEventListener('blur', this.keyup.bind(this));
this.search(this.initial);
}
};
VM.init();
window.VM = VM;
})();