-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
63 lines (56 loc) · 1.63 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
// Replace with your own access key
const ACCESS_KEY =
"Get your own access key from https://unsplash.com/developers";
// Define the base URL and endpoint
const BASE_URL = "https://api.unsplash.com/";
const ENDPOINT = "photos/random";
const COUNT = 30;
// Construct the full URL with query parameters
const url = `${BASE_URL}${ENDPOINT}?client_id=${ACCESS_KEY}&count=${COUNT}`;
// Global variables
const gallery = document.querySelector(".image-container");
const getImages = async () => {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
return console.log(error);
}
};
const setAttributes = (element, attributes) => {
for (const key in attributes) {
element.setAttribute(key, attributes[key]);
}
};
const displayImages = async () => {
try {
const images = await getImages();
imagesLoaded = 0;
totalImages = images.length;
images.forEach((image) => {
const item = document.createElement("a");
setAttributes(item, {
href: image.links.html,
target: "_blank",
});
const img = document.createElement("img");
setAttributes(img, {
src: image.urls.regular,
alt: image.alt_description,
title: image.alt_description,
});
item.appendChild(img);
gallery.appendChild(item);
});
} catch (error) {
console.log("error");
}
};
// loads images as the user scrolls
window.addEventListener("scroll", () => {
const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
if (clientHeight + scrollTop >= scrollHeight - 5) {
displayImages();
}
});