odin-simple-image-slider/index.js

85 lines
2.7 KiB
JavaScript

import "./style.css"
import { createElement, ChevronRight, ChevronLeft, Dot } from 'lucide';
export default function imageSlider(...images) {
const imageSliderHTML = document.createElement("div");
imageSliderHTML.classList.add('image-slider');
const imageContainer = document.createElement("div");
imageContainer.classList.add("slider-image-container");
imageContainer.style.cssText = `
--translate-by: -0vw;
transform: translateX(var(--translate-by));
`;
images.forEach(image => {
const element = new Image();
element.src = image;
element.classList.add("slider-image");
imageContainer.append(element)
})
imageSliderHTML.append(imageContainer);
const left = createElement(ChevronLeft);
left.classList.add("slider-btn-left", "slider-btn");
const right = createElement(ChevronRight);
right.classList.add("slider-btn-right", "slider-btn");
imageSliderHTML.append(left, right);
function updateDots() {
let currentPic = -parseInt(imageContainer.style.getPropertyValue('--translate-by')) / 100;
dots.childNodes.forEach(dot => {
dot.style.stroke = "gray";
})
dots.children[currentPic].style.stroke = "white";
}
left.addEventListener("click", () => {
clearInterval(myInterval);
let currentPic = -parseInt(imageContainer.style.getPropertyValue('--translate-by')) / 100;
if (currentPic <= 0) {
imageContainer.style.setProperty('--translate-by', `-${images.length-1}00vw`)
} else {
imageContainer.style.setProperty('--translate-by', `-${currentPic - 1}00vw`)
}
updateDots();
myInterval = setInterval(next, 6000);
})
function next() {
clearInterval(myInterval);
let currentPic = -parseInt(imageContainer.style.getPropertyValue('--translate-by')) / 100;
if (currentPic + 1 > images.length - 1) {
imageContainer.style.setProperty('--translate-by', `-0vw`)
} else {
imageContainer.style.setProperty('--translate-by', `-${currentPic + 1}00vw`)
}
updateDots();
myInterval = setInterval(next, 6000);
}
right.addEventListener("click", next)
let myInterval = setInterval(next, 6000);
const dots = document.createElement("div");
dots.classList.add("dots-contain")
for (let i in images) {
const dot = createElement(Dot);
dot.classList.add("slider-dot");
dot.addEventListener("click", () => {
imageContainer.style.setProperty('--translate-by', `-${i}00vw`)
updateDots(i);
})
dots.append(dot);
}
imageSliderHTML.append(dots);
updateDots();
return imageSliderHTML;
}