Website Summary Files Commits Branches @commit @diff @stats
path: root / wp-content / themes / carmag / assets / src / scripts / inc / carousel.js
blob: 9d9e701207e62114b94a448e9c3c076ec84ae946 (plain) (blame)
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
class Carousel {
	constructor(forward, backward, images, counter, smallImages) {
		this.forward = forward;
		this.backward = backward;
		this.images = images;
		this.counter = counter;
		this.smallImages = smallImages;
		this.init();
	}
	init() {
		this.imageNum = 0;
		this.counter.textContent = `1/${this.images.length}`;
		this.forward.addEventListener("click", this.forwardHandler.bind(this));
		this.backward.addEventListener(
			"click",
			this.backwardHandler.bind(this)
		);
		this.smallImages.forEach((i, index) => {
			i.addEventListener("click", () => {
				this.imageNum = index;
				this.onSlideHandler();
			});
		});
	}
	onSlideHandler() {
		this.counter.textContent = `${this.imageNum + 1}/${images.length}`;

		this.smallImages.forEach((i) => {
			i.style.transform = `translate(${
				-this.imageNum * (i.clientWidth + 16)
			}px)`;
		});

		this.images.forEach((i) => {
			i.style.transform = `translate(${
				-this.imageNum * i.clientWidth
			}px)`;
		});
	}
	backwardHandler() {
		this.imageNum = !this.imageNum
			? this.images.length - 1
			: this.imageNum - 1;
		this.onSlideHandler();
	}
	forwardHandler() {
		this.imageNum =
			this.imageNum === this.images.length - 1 ? 0 : this.imageNum + 1;
		this.onSlideHandler();
	}
}

const carosel = document.querySelector(".carousel");
const forward = document.querySelector(".forward");
const backward = document.querySelector(".backward");
const images = carosel?.querySelectorAll(".carousel-image");
const counter = carosel?.querySelector(".image-num");
const wraper = document.querySelector(".all-images");
const smallImages = wraper?.querySelectorAll("img");

if (carosel) {
	new Carousel(forward, backward, images, counter, smallImages);
}