-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
92 lines (91 loc) · 3.11 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
91
92
class PhotoGallery{
constructor(){
this.API_KEY = '563492ad6f91700001000001f66917582349437293408ee666dbf4ec';
this.galleryDIv = document.querySelector('.gallery');
this.searchForm = document.querySelector('.header form');
this.loadMore = document.querySelector('.load-more');
this.logo = document.querySelector('.logo')
this.pageIndex = 1;
this.searchValueGlobal = '';
this.eventHandle();
}
eventHandle(){
document.addEventListener('DOMContentLoaded',()=>{
this.getImg(1);
});
this.searchForm.addEventListener('submit', (e)=>{
this.pageIndex = 1;
this.getSearchedImages(e);
});
this.loadMore.addEventListener('click', (e)=>{
this.loadMoreImages(e);
})
this.logo.addEventListener('click',()=>{
this.pageIndex = 1;
this.galleryDIv.innerHTML = '';
this.getImg(this.pageIndex);
})
}
async getImg(index){
this.loadMore.setAttribute('data-img', 'curated');
const baseURL = `https://api.pexels.com/v1/curated?page=${index}&per_page=15`;
const data = await this.fetchImages(baseURL);
this.GenerateHTML(data.photos)
console.log(data)
}
async fetchImages(baseURL){
const response = await fetch(baseURL, {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: this.API_KEY
}
});
const data = await response.json();
// console.log(data);
return data;
}
GenerateHTML(photos){
photos.forEach(photo=>{
const item= document.createElement('div');
item.classList.add('item');
item.innerHTML = `
<a href='${photo.src.original}' target="_blank">
<img src="${photo.src.medium}">
<h3>${photo.photographer}</h3>
</a>
`;
this.galleryDIv.appendChild(item)
})
}
async getSearchedImages(e){
this.loadMore.setAttribute('data-img', 'search');
e.preventDefault();
this.galleryDIv.innerHTML='';
const searchValue = e.target.querySelector('input').value;
this.searchValueGlobal = searchValue;
const baseURL = `https://api.pexels.com/v1/search?query=${searchValue}&page=1&per_page=12`
const data = await this.fetchImages(baseURL);
this.GenerateHTML(data.photos);
e.target.reset();
}
async getMoreSearchedImages(index){
// console.log(searchValue)
const baseURL = `https://api.pexels.com/v1/search?query=${this.searchValueGlobal}&page=${index}&per_page=12`
const data = await this.fetchImages(baseURL);
console.log(data)
this.GenerateHTML(data.photos);
}
loadMoreImages(e){
let index = ++this.pageIndex;
const loadMoreData = e.target.getAttribute('data-img');
if(loadMoreData === 'curated'){
// load next page for curated]
this.getImg(index)
}else{
// load next page for search
this.getMoreSearchedImages(index);
}
}
}
const gallery = new PhotoGallery;