Home > Software design >  How can i make my image carousal loop in vanilla javascript?
How can i make my image carousal loop in vanilla javascript?

Time:07-27

I have created a simple image carousal but I would like it to go back to the start when the final slide item is reached so it appears to have a loop

My HTML:

<div  id="slider">

        <img  src="/assets/image-slide-1.jpg" alt="">
        <img  src="/assets/image-slide-2.jpg" alt="">
        <img  src="/assets/image-slide-3.jpg" alt="">
        <img  src="/assets/image-slide-4.jpg" alt="">
        <img  src="/assets/image-slide-5.jpg" alt="">
    </div>
    <div >
        <button id="prev">
            <img src="/assets/icon-arrow-left.svg" alt="">
        </button>
        <button id="next">
            <img src="/assets/icon-arrow-right.svg" alt="">
        </button>

My JavaScript:

const slidesContainer = document.getElementById("slider");
const slide = document.querySelector(".slide");
const prevButton = document.getElementById("prev");
const nextButton = document.getElementById("next");



nextButton.addEventListener("click", (event) => {
    const slideWidth = slide.clientWidth;
      slidesContainer.scrollLeft  = slideWidth;

  });

  prevButton.addEventListener("click", () => {
    const slideWidth = slide.clientWidth;
    slidesContainer.scrollLeft -= slideWidth;
  });

CodePudding user response:

If width (height, if slider is vertical) of slider is as long as, say, two images, place copies of last two images to the beginning of slider and whenever user reaches the end of slider move it to the very beginning

CodePudding user response:

For the nextButton event handler function you could add a conditional:

if (slidesContainer.scrollLeft >= slideWidth * 4) {
    slidesContainer.scrollLeft = 0;
}

and for the prevButton you would do the opposite:

if (slidesContainer.scrollLeft <= 0) {
    slidesContainer.scrollLeft = scrollWidth * 4;
}
  • Related