stackoverflow.com/questions/62477861 - solution-improve
solution-improve
by MerkUriy
HTML
<!DOCTYPE html>
<html>
<head>
<title>Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div class="carousel-container">
<i class="fa fa-angle-left" id="prevBtn"></i>
<i class="fa fa-angle-right" id="nextBtn"></i>
<div class="carousel-slide">
<img src="//dummyimage.com/500x250.png/f09/fff&text=5" title="clone last" />
<img src="//dummyimage.com/500x250.png/09f/fff&text=1" title="first" />
<img src="//dummyimage.com/500x250.png/90f/fff&text=2" />
<img src="//dummyimage.com/500x250.png/9f0/fff&text=3" />
<img src="//dummyimage.com/500x250.png/f90/fff&text=4" />
<img src="//dummyimage.com/500x250.png/f09/fff&text=5" title="last" />
<img src="//dummyimage.com/500x250.png/09f/fff&text=1" title="clone first" />
<img src="//dummyimage.com/500x250.png/90f/fff&text=2" title="clone two" />
</div>
</div>
</body>
</html>
CSS
html, body {
margin: 0;
padding: 0;
}
.carousel-slide {
width: 100%;
padding-left: 5vw;
display: flex;
flex-wrap: nowrap;
}
.carousel-slide img {
display: block;
margin: 0;
padding: 0;
min-width: 90vw;
}
JavaScript
const carouselSlide = document.querySelector(".carousel-slide");
const carouselImages = document.querySelectorAll(".carousel-slide img");
const prevBtn = document.querySelector("#prevBtn");
const nextBtn = document.querySelector("#nextBtn");
let counter = 1;
let durationAnimation = 400; // ms
let activeAnimation = "transform " + durationAnimation + "ms ease-in-out";
const size = carouselImages[0].clientWidth;
const updateSlideTransformX = () => {
carouselSlide.style.transform = "translateX(" + -size * counter + "px)";
};
const changeActiveAnimation = off => {
carouselSlide.style.transition = off === false ? "" : activeAnimation;
};
updateSlideTransformX();
let interval = 1000; // 1000 * 3 sec
setInterval(function() {
// enable animation
if (counter === 1) changeActiveAnimation()
// to next slide
counter++;
updateSlideTransformX();
if (counter >= carouselImages.length - 2) {
counter = 1;
setTimeout(() => {
// disable animation & jump to slide 1
changeActiveAnimation(false);
updateSlideTransformX();
}, durationAnimation);
}
}, interval);