-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcarousel.js
56 lines (49 loc) · 1.29 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
const carousel = document.querySelector('.carousel');
const container = document.querySelector('.carousel-container');
const items = document.querySelectorAll('.carousel-item');
const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');
let index = 0;
let interval = 0;
function updateCarousel() {
container.style.transform = `translateX(${-index * carousel.offsetWidth}px)`;
}
function setActiveItem() {
items.forEach(item => item.classList.remove('active'));
items[index].classList.add('active');
}
function autoScroll() {
if (interval != 0) return;
interval = setInterval(() => {
index++;
if (index >= items.length) {
index = 0;
}
updateCarousel();
setActiveItem();
}, 4000);
}
prevBtn.addEventListener('click', () => {
index--;
if (index < 0) {
index = items.length - 1;
}
clearInterval(interval);
interval = 0;
setTimeout(autoScroll, 5000);
updateCarousel();
setActiveItem();
});
nextBtn.addEventListener('click', () => {
index++;
if (index >= items.length) {
index = 0;
}
clearInterval(interval);
interval = 0;
setTimeout(autoScroll, 5000);
updateCarousel();
setActiveItem();
});
setActiveItem();
autoScroll();