-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
42 lines (35 loc) · 1.51 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
// Elements selected on the DOM and assigned to variables
const searchForm = document.getElementById('searchForm')
const searchField = document.getElementById('searchField')
const submitBtn = document.getElementById('submitBtn')
const imageDiv = document.getElementById('imageContainer')
// Parts of our Giphy endpoint
const BASEURL = 'https://api.giphy.com/v1/gifs/search?q='
const APIKEY = '&api_key=dc6zaTOxFJmzC&limit=20'
// Function that returns a fetch request to the base URL with passed query
const search = query => {
console.log(`the search term is ${query}`)
return (newSearch = () => fetch(`${BASEURL}${query}${APIKEY}&rating=pg`))
}
// Event listener for the submit button
searchForm.addEventListener('submit', e => {
// Prevent page from reloading when submit is clicked
e.preventDefault()
// Local variable for the value of searchField when the function is invoked
let searchTerm = searchField.value
// Clear out any previous results
imageDiv.innerText = ''
// Invoke our search function and return a function call to displayImages with the images passed in
search(searchTerm)()
.then(result => result.json())
.then(images => {
return displayImages(images.data)
})
})
// Helper function to map over our returned images and display each of them in the `imageDiv` element
const displayImages = images => {
images.map(
image =>
(imageDiv.innerHTML += `<li><img src=${image.images.downsized.url} key=${image.id}></li>`)
)
}