Home > OS >  how do i create a carousel that slides on next and previous button click, the carousel should switch
how do i create a carousel that slides on next and previous button click, the carousel should switch

Time:12-20

i want a slide effect that switches between divs on a click of a button, next and previous

<div >
    <div >
        <div>slide 1</div>
        <div>slide 2</div>
        <div>slide 3</div>
        <div>slide 4</div>
    </div>
    <button>1</button>
    <button>2</button>
</div>

deleted most of the codes i tried.

<div >
    <div >
        <div>slide 1</div>
        <div>slide 2</div>
        <div>slide 3</div>
        <div>slide 4</div>
    </div>
    <button>1</button>
    <button>2</button>
</div>

CodePudding user response:

It doesn't matter whether you have images or divs. The mechanism is the same. You basically set initial active slide and create functions to go to previous or next slide. Every time you need to check if active slide is the first/last slide.

const slides = document.querySelectorAll(".carousel div")
const firstSlide = 0
const lastSlide = slides.length - 1
let activeSlide = 0

const goToPreviousSlide = () => {
  slides[activeSlide].classList.remove("active")
  if (activeSlide !== firstSlide) {
    activeSlide = activeSlide - 1
  } else {
    activeSlide = lastSlide
  }
  slides[activeSlide].classList.add("active")
}

const goToNextSlide = () => {
  slides[activeSlide].classList.remove("active")
  if (activeSlide !== lastSlide) {
    activeSlide = activeSlide   1
  } else {
    activeSlide = firstSlide
  }
  slides[activeSlide].classList.add("active")
}
.container {
  display: flex;
}
.carousel {
  padding: 2rem;
}
.carousel div {
  display: none;
}
.carousel div.active {
  display: block;
}
<div >
    <button onclick="goToPreviousSlide()">Previous</button>
    <div >
        <div >slide 1</div>
        <div>slide 2</div>
        <div>slide 3</div>
        <div>slide 4</div>
    </div>
    <button onclick="goToNextSlide()">Next</button>
</div>

  • Related