Need some helps

I’ve written an image sliding function

let indx2 = 0;
doSlide2();

function doSlide2() {
    let k;
    let z = document.getElementsByClassName("mySlide3");
    for (k = 0; k < z.length; k++) {
       z[k].style.display = "none";  
    }
    indx2++;
    if (indx2 > z.length) {indx2 = 1}    
    z[indx2-1].style.display = "block";  
    setTimeout(doSlide2, 4000); // Change image every 2 seconds
}

but it works only for one container and if i want to use it somewhere else i should rewrite all the function.
what should i do to be able to use only one function for many containers?
best regards

This isn’t tested, and i think there’ll need to be more modifications, but as a start:

// Pass the class name in
function doSlide2(slidesClass) {
    // Move the indexer inside the function
    let indx2 = 0;
    let k;
    // use the class name
    let z = document.getElementsByClassName(slidesClass);
    
    for (k = 0; k < z.length; k++) {
       z[k].style.display = "none";  
    }
    indx2++;
    if (indx2 > z.length) {indx2 = 1}    
    z[indx2-1].style.display = "block";  
    setTimeout(doSlide2, 4000); // Change image every 2 seconds
}

Which you can call like

doSlide2('mySlide3');
doSlide2('mySlide4');

Pass more values into the function if you want to configure it more.

Also it would be better to pass in the id/class for the container for the slider, then instead of let z = document.getElementsByClassName("mySlide3");, just do something like:

function doSlide2(sliderId) {
  // ........
  let z = document.querySelectorAll(`${sliderId} .mySlide3`);
  // ........
}

Which you can call like

doSlide2('#slider1');
doSlide2('#slider2');
2 Likes

Do you have a demo page or a codepen?

1 Like

thanks for your help but i couldn’t do it dough I tried a lot

There you are

The HTML and JS code is already written

try to cut down on the JavaScript

we have keyframes that already simulate movement and those automatically give us a lot of control

1 Like

good suggestion
thanks

You need an index for each specific one, removing the global index is what killed it

function slide(sId) {
    let indx = 0;
    
    function doSlide() {
      console.log(`Current slide index for ${sId} is ${indx}`);
      let i;
      let x = document.getElementsByClassName(sId);
      for (i = 0; i < x.length; i++) {
         x[i].style.display = "none";  
      }
      indx++;
      if (indx > x.length) {indx = 1}    
      x[indx-1].style.display = "block";
      setTimeout(doSlide, 4000);
    }
    doSlide();
}

slide('mySlide1');
slide('mySlide2');
slide('mySlide3');
slide('mySlide4');
1 Like