I've created an image slider using HTML and JS. One problem I've come across that I cant quite work myself around is how the image slider transmits multiple images for each slide when the dimensions of the image does not perfectly fit the box. I would like to change this code so that there is only one image displayed at a single time + the image is centered to the box. Does anyone have any suggestions on to how I would edit this? Please let me know if any additional information is needed.
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;
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.tranisition = "transform 0.4s ease-in-out"
counter++;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
});
prevBtn.addEventListener('click', () => {
if (counter <= 0) {
return;
}
carouselSlide.style.tranisition = "transform 0.4s ease-in-out"
counter--;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
});
carouselSlide.addEventListener('transitonend', () => {
if (carouselImages[counter].id === 'lastclone') {
carouselSlide.style.transition = "none";
counter = carouselImage.length - 2;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
}
if (carouselImages[counter].id === 'firstclone') {
carouselSlide.style.transition = "none";
counter = carouselImage.length - counter;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
}
});
<div class="carousel-container">
<i class="fa fa-arrow-left" id="prevBtn" aria-hidden="true"></i>
<i class="fa fa-arrow-right" id="nextBtn" aria-hidden="true"></i>
<div class="carousel-slide">
<img src="public/images/homme.jpeg" id="lastClone" alt="">
<img src="public/images/homme.jpeg" alt="">
<img src="public/images/homme.jpeg" alt="">
<img src="public/images/homme.jpeg" alt="">
<img src="public/images/homme.jpeg" id="firstClone" alt="">
</div>
</div>
</div>
One option would be to place each image in the center of its own container div that has the size of the largest image, line up those divs, and have your carouselSlide slide over those divs, so that it only shows one div at a time.
This may produce margins for images that are smaller than the largest image. One way to solve that is to use CSS to set the images as background images of the divs, and use CSS to center the images and fill the div.