69 lines
1.9 KiB
JavaScript
69 lines
1.9 KiB
JavaScript
function initCarousel(id) {
|
|
document.addEventListener("DOMContentLoaded", function () {
|
|
const track = document.getElementById(id);
|
|
const originalSlides = Array.from(track.children);
|
|
const total = originalSlides.length;
|
|
|
|
if (total <= 1) {
|
|
return;
|
|
}
|
|
|
|
const firstClone = originalSlides[0].cloneNode(true);
|
|
const lastClone = originalSlides[total - 1].cloneNode(true);
|
|
track.appendChild(firstClone);
|
|
track.insertBefore(lastClone, originalSlides[0]);
|
|
|
|
let current = 1;
|
|
let isTransitioning = false;
|
|
track.style.transform = `translateX(-${current * 100}%)`;
|
|
|
|
const dots = document.querySelectorAll(`.${id}_dot`);
|
|
|
|
function updateDots(index) {
|
|
const realIndex = (index - 1 + total) % total;
|
|
dots.forEach((d, i) => {
|
|
d.classList.toggle("opacity-100", i === realIndex);
|
|
d.classList.toggle("opacity-50", i !== realIndex);
|
|
});
|
|
}
|
|
|
|
function goTo(index) {
|
|
if (isTransitioning) return;
|
|
isTransitioning = true;
|
|
track.style.transition = "transform 500ms ease-in-out";
|
|
current = index;
|
|
track.style.transform = `translateX(-${current * 100}%)`;
|
|
updateDots(current);
|
|
}
|
|
|
|
function next() {
|
|
goTo(current + 1);
|
|
}
|
|
function prev() {
|
|
goTo(current - 1);
|
|
}
|
|
|
|
track.addEventListener("transitionend", function () {
|
|
if (current === 0) {
|
|
track.style.transition = "none";
|
|
current = total;
|
|
track.style.transform = `translateX(-${current * 100}%)`;
|
|
}
|
|
if (current === total + 1) {
|
|
track.style.transition = "none";
|
|
current = 1;
|
|
track.style.transform = `translateX(-${current * 100}%)`;
|
|
}
|
|
|
|
isTransitioning = false;
|
|
});
|
|
|
|
setInterval(next, 5000);
|
|
updateDots(current);
|
|
|
|
window[`${id}_goTo`] = (i) => goTo(i + 1);
|
|
window[`${id}_next`] = next;
|
|
window[`${id}_prev`] = prev;
|
|
});
|
|
}
|