-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (52 loc) · 1.48 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
const key = '&api_key=3meK41RxJiNeS6c81jqYQ5Fzqtiq0p0j&limit=20';
const url = 'https://api.giphy.com/v1/gifs/';
const button = document.querySelector('button');
const input = document.querySelector('input');
const results = document.querySelector('.results');
let prevInput;
let title;
const fetchData = async (search) => {
let urlBase;
!search
? (urlBase = `${url}trending?${key}`)
: (urlBase = `${url}search?q=${search}${key}`);
try {
const response = await fetch(urlBase);
return await response.json();
} catch (error) {
throw new Error(error);
}
};
const handleData = async (e) => {
e.preventDefault();
title && title.remove();
if (prevInput === input.value) return;
prevInput = input.value;
const res = await fetchData(input.value);
res.data.forEach((val) => {
let image = document.createElement('img');
image.src = val.images.fixed_height_still.url;
image.classList.add('image');
results.prepend(image);
image.addEventListener('mouseenter', () => {
image.src = val.images.fixed_height.url;
});
image.addEventListener('mouseleave', () => {
image.src = val.images.fixed_height_still.url;
});
});
input.value = '';
};
window.addEventListener('load', (e) => {
handleData(e);
title = document.createElement('h2');
title.textContent = 'Trending';
results.before(title);
});
button.addEventListener('click', (e) => {
if (input.value === '') {
e.preventDefault();
return;
}
handleData(e);
});