user19632560
user19632560

Reputation:

How can i make my image carousal loop in vanilla javascript?

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 class="slider" id="slider">

        <img class="slide" src="/assets/image-slide-1.jpg" alt="">
        <img class="slide" src="/assets/image-slide-2.jpg" alt="">
        <img class="slide" src="/assets/image-slide-3.jpg" alt="">
        <img class="slide" src="/assets/image-slide-4.jpg" alt="">
        <img class="slide" src="/assets/image-slide-5.jpg" alt="">
    </div>
    <div class="buttons">
        <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;
  });

Upvotes: 0

Views: 125

Answers (2)

LeKoels27
LeKoels27

Reputation: 35

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;
}

Upvotes: 1

Aziz Hakberdiev
Aziz Hakberdiev

Reputation: 326

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

Upvotes: 0

Related Questions