-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
90 lines (79 loc) · 2.59 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
82
83
84
85
86
87
88
89
90
import { apiKey } from "./api.js";
const key = apiKey;
const gallery = document.querySelector(".gallery");
const searchInput = document.querySelector(".search-input");
const searchForm = document.querySelector("#search-form");
const moreBtn = document.querySelector(".nav-btn");
let searchValue;
let fetchLink;
let page = 1;
let currentSearch;
//? EVENT LISTENERS /////////////////
searchForm.addEventListener("submit", (e) => {
e.preventDefault();
currentSearch = searchValue;
searchPhotos(searchValue);
clear();
});
moreBtn.addEventListener("click", expandPage);
searchInput.addEventListener("input", inputValue);
//////////////////////////////?
//? FUNCTIONS /////////////////////
//* INPUT VALUE ASSIGNED TO GLOBAL VARIABLE - *searchValue*
function inputValue(e) {
searchValue = e.target.value;
}
//* LAYOUT CREATED DYNAMICALLY - TEMPLATE
function generatePictures(data) {
data.photos.forEach((photo) => {
const galleryImage = document.createElement("div");
galleryImage.innerHTML = `<img src=${photo.src.large}></img>
<div class="gallery-info">
<p><a href="${photo.photographer_url}" target="_blank">${photo.photographer}</a></p>
<a href=${photo.src.original} target="_blank">download</a>
</div>
`;
galleryImage.classList.add("gallery-layout");
gallery.appendChild(galleryImage);
});
}
function clear() {
searchInput.value = "";
gallery.innerHTML = "";
}
////////////////////////////////////?
//? ASYNC FUNCTIONS ////////////////
async function fetchApi(url) {
const dataFetch = await fetch(url, {
method: "GET",
headers: {
Accept: "application/json",
Authorization: key,
},
});
const data = await dataFetch.json();
return data;
}
//* CURATED PHOTOS USED FOR INITIAL PAGE
async function curatedPhotos() {
fetchLink = "https://api.pexels.com/v1/curated?per_page=15&page=1";
const dataFetch = await fetchApi(fetchLink);
generatePictures(dataFetch);
}
async function searchPhotos(search) {
fetchLink = `https://api.pexels.com/v1/search?query=${search}+query&per_page=15&page=1`;
const dataFetch = await fetchApi(fetchLink);
generatePictures(dataFetch);
}
async function expandPage() {
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();