Home > Mobile >  how to run a loop function multiple times on similar elements - js
how to run a loop function multiple times on similar elements - js

Time:01-06

I have this function that loops through divs (cards) and every 3 seconds shoe the next one. kind of a slide show, a gallery.

I wish to run this function on multiple "galleries" (that are built exactly the same). How can I acheieve that?

here's the js that right now collect all 'cards' in the page, I want it to take the cards of each gallery and run it on the gallery itself:

var slideIndex = 0;
showSlides();

function showSlides() {
  var i;
  var slides = document.getElementsByClassName("card");

  for (i = 0; i < slides.length; i  ) {
    slides[i].style.opacity = "0";
  }
  slideIndex  ;
  if (slideIndex > slides.length) {slideIndex = 1}
  slides[slideIndex-1].style.opacity = "1";
  setTimeout(showSlides, 3000);
}

I hope I'm being understood - thanks a lot in advance!

CodePudding user response:

You almost achieve it : )

function slideIt(elementId) {
  var slideIndex = 0;
  // showSlides();

  function showSlides() {
    var i;
    // var slides = document.getElementsByClassName("card");
    var slides = document.getElementsById(elementId);
    // ....
  }
  showSlides();
}
slideIt("card1")
slideIt("card2")

CodePudding user response:

I used this eventually and it works great:

const elements = document.querySelectorAll('.today-show');
var timer = document.getElementById('timer').innerHTML;


function intervalFunction(slideIndex) {

    var i;
    const currentElement = this;

    var slides = currentElement.querySelectorAll(".home-show-title");

    for (i = 0; i < slides.length; i  ) {
    slides[i].classList.remove('home-title-appear');
    }
    setTimeout(function(){
        slides[slideIndex].classList.add('home-title-appear');
    },800)
}

elements.forEach(element => {
    const boundIntervalFunction = intervalFunction.bind(element);
    let slideIndex = 1;
    setInterval(() => {
        boundIntervalFunction(slideIndex);
        slideIndex  ;
        if (slideIndex > 2) {slideIndex = 0 }
    }, timer "000"); 
});

thanks for the help!

  • Related