-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
92 lines (79 loc) · 2.8 KB
/
Copy pathmain.js
File metadata and controls
92 lines (79 loc) · 2.8 KB
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
console.log('JS is here boo!');
const search = document.createElement('div');
let input = document.createElement('input');
input.type = 'text';
search.appendChild(input);
let searchBaseUrl = 'https://itunes.apple.com/search?term=';
let searchForm = document.querySelector('#search-form')
searchForm.addEventListener('submit', (event) => {
event.preventDefault()
console.log('submitted!')
let searchBox = document.querySelector('#search-box')
let searchUrl = `${searchBaseUrl}${searchBox.value}`
console.log('search url', searchUrl)
getSearchResults(searchUrl)
})
function getSearchResults(url) {
fetch(url, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
})
//response is whatever the fetch returns
.then(response => {
if(!response.ok){
throw Error(response.status);
} else {
console.log(response);
return response.json();
}
})
// data is whatever the above code returns, in this case response.json()
.then(data => {
let songs = data.results;
showResults(songs);
}).catch(error => {
console.log(error);
alert(`Your request failed, for the reason: ${error}`);
})
}
let resultsDiv = document.querySelector('#results');
console.log('results div', resultsDiv);
function showResults(songArray) {
resultsDiv.innerHTML = ('')
console.log(songArray);
if (songArray.length === 0) {
resultsDiv.innerText = `Uh oh! I couldn't find music to match your search. Please try again`;
} else {
for (let song of songArray){
let recordDiv = document.createElement('div');
recordDiv.classList.add('record');
let imageDiv = document.createElement('img');
imageDiv.classList.add('image');
imageDiv.src = song.artworkUrl100;
let titleDiv = document.createElement('div');
titleDiv.classList.add('div');
titleDiv.innerText = `${song.trackName}`;
let artistDiv = document.createElement('div');
artistDiv.classList.add('div');
artistDiv.innerText = `${song.artistName}`;
resultsDiv.appendChild(recordDiv);
recordDiv.appendChild(imageDiv);
recordDiv.appendChild(titleDiv);
recordDiv.appendChild(artistDiv);
let audio = document.querySelector('#audio-preview')
let currentSong = document.querySelector('.current-song')
recordDiv.addEventListener('click', playCrackle);
function playCrackle() {
const crackle = new Audio('resources/crackle.mp3');
crackle.play();
}
function playAudio() {
audio.src = song.previewUrl
currentSong.innerText = `Currently playing: ${song.trackName} by ${song.artistName}`
audio.play();
}
recordDiv.addEventListener('click', e =>
setTimeout(playAudio, 1800)
)}
}
}