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`);
// ........
}
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');