-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
46 lines (36 loc) · 1.16 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
let input = document.querySelector('input');
let displayImages = document.querySelector('.display-images');
const url = 'https://api.unsplash.com/photos/?client_id=TUe9u2c1QPZ2zpbKVv7z7AHI-UoADAy8jJ2aFNSshWU';
// const url = 'https://picsum.photos/v2/list?page=2&limit=10';
const searchURL = (query) => {
return `https://api.unsplash.com/search/photos/?query=${query}&client_id=TUe9u2c1QPZ2zpbKVv7z7AHI-UoADAy8jJ2aFNSshWU`;
};
function fetch(url, successHandler) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = () => {
successHandler(JSON.parse(xhr.response));
};
xhr.onerror = function() {
console.error('Something is wrong 🙁');
};
xhr.send();
}
function displayImg(images) {
displayImages.innerHTML = "";
images.forEach((image) => {
let img = document.createElement('img');
img.src = image.urls.small;
displayImages.append(img);
});
}
fetch(url, displayImg);
function handleSearch(event) {
if(event.keyCode === 13 && input.value) {
fetch(searchURL(input.value), (searchResults) => {
displayImg(searchResults.results);
});
input.value = '';
}
}
input.addEventListener('keyup', handleSearch);