'JavaScript Image Carousel
I made an image carousel with JavaScript and I'm running into an issue where when the page first loads, it loads like the below image. If I refresh, it then adjusts properly. I'm hoping someone can give me a tip on how to fix that? I'm including the code below.
script.js
const carouselSlide = document.querySelector('.carousel-slide');
const carouselImages = document.querySelectorAll('.carousel-slide img');
// buttons
const prevBtn = document.querySelector('#prevBtn');
const nextBtn = document.querySelector('#nextBtn');
// counter
let counter = 1;
const size = carouselImages[0].clientWidth;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
// button listeners
nextBtn.addEventListener('click',()=> {
if (counter >= carouselImages.length -1) return;
carouselSlide.style.transition = "transform 0.4s ease-in-out";
counter++;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
});
prevBtn.addEventListener('click',()=> {
if (counter <= 0) return;
carouselSlide.style.transition = "transform 0.4s ease-in-out";
counter--;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
});
carouselSlide.addEventListener('transitionend', ()=>{
if (carouselImages[counter].id === 'lastClone'){
carouselSlide.style.transition = "none";
counter = carouselImages.length -2;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
}
if (carouselImages[counter].id === 'firstClone'){
carouselSlide.style.transition = "none";
counter = carouselImages.length - counter;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
}
});
The HTML for the carousel; the tutorial I was following had me do a firstclone and lastclone to create a more seamless transition.
<!-- begin carousel -->
<div class="carousel-container">
<!-- carousel buttons -->
<i class="fa-solid fa-arrow-left" id="prevBtn"></i>
<i class="fa-solid fa-arrow-right" id="nextBtn"></i>
<!-- begin carousel images -->
<div class="carousel-slide">
<img src="img5" id="lastClone">
<img src="img1">
<img src="img2">
<img src="img3">
<img src="img4">
<img src="img5">
<img src="img1">
<!-- end carousel images -->
</div>
<!-- end carousel -->
</div>
The carousel stylesheet
/* carousel style */
.carousel-slide img {
width: 100vw;
margin: auto;
}
.carousel-container {
overflow: hidden;
margin:0;
padding:0;
}
.carousel-slide {
display: flex;
width: 100%;
height:100vh;
}
#prevBtn, #nextBtn {
position: absolute;
top: 40%;
z-index:10;
font-size: 30px;
color: white;
opacity: 0.9;
cursor: pointer;
padding: 10px;
}
#prevBtn {
left: 3%;
}
#nextBtn {
right: 3%;
}
#prevBtn:hover, #nextBtn:hover {
background-color: rgba(0,0,0,0.4);
}
UPDATE: Added the CSS and HTML to hopefully help with identifying the problem. Thank you so much in advance!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

