Search code examples
javascripthtmlcssclasscycle

How do I cycle a css class through banners in a slider container with javascript?


I have a basic slider setup, with three banners in it. The id is there to set the background image. Only the banner with the class "active" is shown at the frontend.

I'd like to cycle that class within the elements in the "slider" div every 8 seconds, so I can add new banners in the html and they will be implemented in the loop easily.

My initial approach only works, if two banners are active within the slider.

setInterval(changebanner, 8000);

function changebanner() {
  document.getElementsByClassName("banner").classList.toggle("active");
}
<div class="slider">
  <div class="banner active" id="sky"></div>
  <div class="banner" id="outdoor"></div>
  <div class="banner" id="photo"></div>
</div>


Solution

  • You need to track the current slide - see code below (comments in js)

    const banners = document.getElementsByClassName("banner"); // get banners
    let currentActive = 0;  // set the current active slide index
    setInterval(changebanner, 2000); // have changed to 2000 for demo so you don't have to wait 8 seconds
    
    function changebanner() {
      banners[currentActive].classList.remove("active"); // remove class from current active banner
    
      currentActive++; // increment active slide
    
      if (currentActive === banners.length) {
        currentActive = 0; // reset active to 0 if last banner is active
      }
    
      banners[currentActive].classList.add("active"); // add active to next slide
    }
    .active {
      color: red;
    }
    <div class="slider">
      <div class="banner active" id="sky">1</div>
      <div class="banner" id="outdoor">2</div>
      <div class="banner" id="photo">3</div>
    </div>