-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcarousel.js
74 lines (58 loc) · 2.34 KB
/
carousel.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
const carousels = document.querySelectorAll("[data-carousel]");
carousels.forEach((carousel) => {
const prev = carousel.querySelector("[data-direction=previous]");
const next = carousel.querySelector("[data-direction=next]");
const paginationDots = carousel.querySelectorAll("[data-pagination-dot]");
const scrollContainer = carousel.querySelector("[data-scroll]");
const scrollItems = [...scrollContainer.querySelectorAll("[data-item]")];
const options = {
root: scrollContainer,
rootMargin: `0px`,
threshold: 0.9,
};
const setActiveIndex = (index) => {
paginationDots.forEach((dot) => {
dot.setAttribute("aria-selected", false);
});
paginationDots[index]?.setAttribute("aria-selected", true);
};
setActiveIndex(0)
const onIntersect = (entries, observer) => {
entries.forEach((entry, index) => {
if (entry.isIntersecting) {
const visibleItem = entry.target;
if (visibleItem.dataset.itemIndex) {
setActiveIndex(Number.parseInt(visibleItem.dataset.itemIndex));
} else {
setActiveIndex(0);
}
}
});
};
const observer = new IntersectionObserver(onIntersect, options);
scrollItems.forEach((item) => {
observer.observe(item);
});
const onPrevNextClick = (event) => {
event.preventDefault();
const target = event.currentTarget;
const distance = scrollContainer.offsetWidth;
const direction = target.dataset.direction;
const scrollTo = direction === "next" ? distance : distance * -1;
scrollContainer.scrollBy({ left: scrollTo, behavior: "smooth" });
};
const onPaginationClick = (event) => {
event.preventDefault();
const distance = scrollContainer.offsetWidth;
const target = event.currentTarget;
if (target.dataset.paginationIndex) {
const index = Number.parseInt(target.dataset.paginationIndex);
scrollContainer.scrollTo({ left: distance * index, behavior: "smooth" });
}
};
prev.addEventListener("click", onPrevNextClick);
next.addEventListener("click", onPrevNextClick);
paginationDots.forEach((dot) => {
dot.addEventListener("click", onPaginationClick);
});
});