-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
60 lines (52 loc) · 1.71 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
const API_URL = 'https://api.unsplash.com/search/photos?client_id=B7RNsPmUh5aJyA0DmQPGTexVmfG_gZFT8u2hUKhDyDc';
const form = document.querySelector('form');
const input = document.querySelector('input');
const loadingImage = document.getElementById('loadingImage');
const imageSection = document.querySelector('.images');
const prevPage = document.querySelector('.previouspage');
const nextPage = document.querySelector('.nextpage');
let page = 1;
loadingImage.style.display = 'none'; //default loading is off
form.addEventListener('submit', (event) => {
page = 1;
formSubmitted(event);
});
prevPage.addEventListener('click', (event) => {
page--;
if(page<1) page=1;
formSubmitted(event);
});
nextPage.addEventListener('click', (event) => {
page++;
formSubmitted(event);
});
function formSubmitted(event) {
event.preventDefault(); //prevent refresh on btn click
//console.log(page);
let searchTerm = input.value;
searchStart(); //show loading image, hide results
search(searchTerm, page) //fetch returna promise
.then(displayImages)
.then(() => {
loadingImage.style.display = 'none';
});
}
function searchStart() {
loadingImage.style.display = '';
imageSection.innerHTML = '';
}
function search(searchTerm, page) {
const url = `${API_URL}&query=${searchTerm}&page=${page}`;
return fetch(url)
.then(response => response.json()) //parse
.then(result => {
return result.results; //api is weird has a results array nested
});
}
function displayImages(images) {
images.forEach(image => {
const imageElement = document.createElement('img');
imageElement.src = image.urls.regular;
imageSection.appendChild(imageElement);
});
}