ldc-cocotte/resources/ts/fo/utilities/sliders.ts
2026-10-27 09:58:12 +01:00

58 lines
1.8 KiB
TypeScript

import type { Carousel } from "bootstrap";
document.addEventListener("DOMContentLoaded", (): void => {
const carouselElement = document.querySelector<HTMLElement>("#products-carousel");
if (carouselElement) {
const carouselInner = carouselElement.querySelector<HTMLElement>(".carousel-inner");
const carouselItems = carouselElement.querySelectorAll<HTMLElement>(".carousel-item");
if (carouselInner && carouselItems.length > 0) {
const updateCarouselLayout = (): void => {
const windowWidth: number = window.innerWidth;
carouselInner.style.display = "flex";
carouselInner.style.flexDirection = "row";
let itemsPerView = 1;
if (windowWidth >= 768 && windowWidth < 992) {
itemsPerView = 2;
}
if (windowWidth >= 992){
itemsPerView = 3;
}
carouselItems.forEach((item: HTMLElement) => {
const widthPercent = 100 / itemsPerView;
item.style.flex = `0 0 ${widthPercent}%`;
item.style.display = "block";
});
};
carouselElement.addEventListener("slide.bs.carousel", (e: Event) => {
const direction = (e as unknown as Carousel.Event).direction;
let itemsPerView = 1;
if (window.innerWidth >= 768) {
itemsPerView = 2;
}
if (window.innerWidth >= 992) {
itemsPerView = 3;
}
const scrollAmount = carouselInner.clientWidth / itemsPerView;
if (direction === "left") {
carouselInner.scrollBy({ left: scrollAmount, behavior: "smooth" });
} else {
carouselInner.scrollBy({ left: -scrollAmount, behavior: "smooth" });
}
e.preventDefault();
});
updateCarouselLayout();
window.addEventListener("resize", updateCarouselLayout);
}
}
});