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

Time:11-28

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 >
  <div  id="sky"></div>
  <div  id="outdoor"></div>
  <div  id="photo"></div>
</div>

CodePudding user response:

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 >
  <div  id="sky">1</div>
  <div  id="outdoor">2</div>
  <div  id="photo">3</div>
</div>

CodePudding user response:

I think this should work as you want.

There we no need to loop over banners we just made and index variable, removed active class from whichever banner it is on and then assigned that to the next banner.


    let currIndex = 0;
    setInterval(changebanner, 8000);
    
    function changebanner() {
       let banners = document.getElementsByClassName("banner");
       let activeBanner = document.getElementByClassName("active");
       activeBanner.classList.remove('active')
       if(currIndex >= banners.length){
           currIndex = 0;
       }
       banners[currIndex].classList.add('active')
       currIndex  ;
    }

  • Related