-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
81 lines (71 loc) · 2.18 KB
/
app.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const auth = "563492ad6f91700001000001f35c7d43778b4ae5975131c8aedfcd59";
const gallery = document.querySelector(".gallery");
const searchInput = document.querySelector(".search-input");
const form = document.querySelector(".search-form");
let searchValue;
const more = document.querySelector(".more");
let page = 1;
let fetchLink;
let currentSearch;
//Event Listeners
searchInput.addEventListener("input", updateInput);
form.addEventListener("submit", (e) => {
e.preventDefault();
currentSearch = searchValue;
searchPhotos(searchValue);
});
more.addEventListener("click", loadMore);
function updateInput(e) {
searchValue = e.target.value;
}
async function fetchApi(url) {
const dataFetch = await fetch(url, {
method: "GET",
headers: {
Accept: "application/json",
Authorization: auth,
},
});
const data = await dataFetch.json();
return data;
}
function generatePictures(data) {
data.photos.forEach((photo) => {
const galleryImg = document.createElement("div");
galleryImg.classList.add("gallery-img");
galleryImg.innerHTML = `
<div class="gallery-info">
<p>${photo.photographer}</p>
<a href="${photo.src.original}">Download</a>
</div>
<img src=${photo.src.large}></img>
`;
gallery.appendChild(galleryImg);
});
}
async function curatedPhotos() {
fetchLink = `https://api.pexels.com/v1/curated?per_page=15&page=1`;
const data = await fetchApi(fetchLink);
generatePictures(data);
}
async function searchPhotos(query) {
clear();
fetchLink = `https://api.pexels.com/v1/search?query=${query}+query&per_page=15&page=1`;
const data = await fetchApi(fetchLink);
generatePictures(data);
}
function clear() {
gallery.innerHTML = "";
searchInput.value = "";
}
async function loadMore() {
page++;
if (currentSearch) {
fetchLink = `https://api.pexels.com/v1/search?query=${currentSearch}+query&per_page=15&page=${page}`;
} else {
fetchLink = `https://api.pexels.com/v1/curated?per_page=15&page=${page}`;
}
const data = await fetchApi(fetchLink);
generatePictures(data);
}
curatedPhotos();