-
Notifications
You must be signed in to change notification settings - Fork 0
/
carousel.js
52 lines (44 loc) · 1.42 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
"use strict";
// Select all slides
const slides = document.querySelectorAll(".slide");
// loop through slides and set each slides translateX
//moves slides from stacked on top of each other to side by side
slides.forEach((slide, indx) => {
slide.style.transform = `translateX(${indx * 100}%)`;
});
// select next slide button
const nextSlide = document.querySelector(".btn-next");
// current slide counter
let curSlide = 0;
// maximum number of slides
let maxSlide = slides.length - 1;
// add event listener and navigation functionality
nextSlide.addEventListener("click", function () {
// check if current slide is the last and reset current slide
if (curSlide === maxSlide) {
curSlide = 0;
} else {
curSlide++;
}
// move slide by -100%
//does the action of moving slides horizontally
slides.forEach((slide, indx) => {
slide.style.transform = `translateX(${100 * (indx - curSlide)}%)`;
});
});
// select next slide button
const prevSlide = document.querySelector(".btn-prev");
// add event listener and navigation functionality
prevSlide.addEventListener("click", function () {
// check if current slide is the first and reset current slide to last
if (curSlide === 0) {
curSlide = maxSlide;
} else {
curSlide--;
}
// move slide by 100%
//moves slides in opposite direction
slides.forEach((slide, indx) => {
slide.style.transform = `translateX(${100 * (indx - curSlide)}%)`;
});
});