-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
102 lines (90 loc) · 2.74 KB
/
script.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
93
94
95
96
97
98
99
100
101
102
const imgContainer = document.getElementById("img-container")
const loader = document.getElementById("loader")
const apiForm = document.getElementById("api-form")
const apiContainer = document.getElementById("api-container")
let photoArray = []
let loaded = false
let load = 0
let totalLoaded = 0
//set unsplash api paramater
const count = 30;
let unsplashUrl = ``
let apiKey = ""
//create setAttribute helper function
const setAttributes = (element, featureObjects) => {
for (let i in featureObjects) {
element.setAttribute(i, featureObjects[i])
}
}
//check if loaded photos
const checkLoaded = () => {
load++
if (load == totalLoaded) {
loaded = true;
}
}
//create link and photo, add to DOM
const displayPhoto = () => {
load = 0
totalLoaded = photoArray.length;
photoArray.forEach((photo => {
const description = photo.description;
const imgSrc = photo.urls.regular;
const link = photo.links.html;
//add <a> for unsplash photo's link
const item = document.createElement("a");
setAttributes(item, {
href: link,
target: "new_Tab"
})
item.classList.add("img-card")
//add <img> for photo
const img = document.createElement("img");
setAttributes(img, {
src: imgSrc,
alt: description,
title: description
})
img.addEventListener("load", checkLoaded)
// check if all img is loaded
// img.addEventListener("load", imgLoaded)
//put img in item and put item in imgContainer
item.appendChild(img);
imgContainer.appendChild(item);
}))
}
// get photo from api
const getPhoto = async () => {
loader.removeAttribute("hidden")
setTimeout(async () => {
try {
const res = await fetch(unsplashUrl);
let datas = await res.json();
photoArray = datas
// console.log(photoArray);
displayPhoto();
loader.setAttribute("hidden", "")
}
catch (e) {
alert("api讀取失敗, 請嘗試正確的api key")
location.reload()
console.log(e)
}
}, "500")
}
// get api key first and then onload
apiForm.addEventListener('submit', (e) => {
e.preventDefault();
apiKey = api.value;
unsplashUrl = `https://api.unsplash.com/photos/random?client_id=${apiKey}&collections=778914&count=${count}`
apiContainer.setAttribute("hidden", "")
//On load
getPhoto()
})
//check if scroll to the buttom and load more photos
window.addEventListener("scroll", () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 400 && loaded == true) {
loaded = false;
getPhoto()
}
})