I have a function that successfully changes the image of a container every 5 seconds. However, I am facing an issue when trying to add 2 containers side by side and change their images simultaneously. When I run the functions for both containers, only one of them starts changing the image while the other remains static. But if I run either function individually, it works correctly and starts changing the image. How can I make both containers change their images every 5 seconds? Any assistance would be greatly appreciated. Thank you in advance.
let index = 0;
const slides1 = document.querySelectorAll(".mainDisplay1 .slide1");
function change1() {
if (++index >= slides1.length)
index = 0;
for (let i = 0; i < slides1.length; i++)
slides1[i].classList.toggle("active1", i == index);
}
const slides2 = document.querySelectorAll(".mainDisplay2 .slide2");
function change2() {
if (++index >= slides2.length)
index = 0;
for (let i = 0; i < slides2.length; i++)
slides2[i].classList.toggle("active2", i == index);
}
//calling one of the 2 functions work but only one of them works when calling both
window.onload = function() {
setInterval(change1, 5000);
};
window.onload = function() {
setInterval(change2, 5000);
};
.mainDisplay1 {
position: absolute;
top: 8%;
left: 0%;
border-radius: 2%;
-webkit-box-shadow: 10px 3px 31px 6px rgba(0, 0, 0, 0.77);
box-shadow: 10px 3px 31px 6px rgba(0, 0, 0, 0.77);
}
.mainDisplay1 img {
width: 50%;
height: 600px;
}
.mainDisplay2 {
position: absolute;
top: 8%;
left: 0%;
border-radius: 2%;
-webkit-box-shadow: 10px 3px 31px 6px rgba(0, 0, 0, 0.77);
box-shadow: 10px 3px 31px 6px rgba(0, 0, 0, 0.77);
}
.mainDisplay2 img {
width: 50%;
height: 600px;
float: right;
}
.slide1 {
width: 100%;
height: 100%;
opacity: 0;
z-index: 1;
-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
-o-transition: opacity 1s;
transition: opacity 1s;
position: absolute;
}
.active1 {
opacity: 1;
z-index: 2;
position: initial;
}
.slide2 {
width: 100%;
height: 100%;
opacity: 0;
z-index: 1;
-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
-o-transition: opacity 1s;
transition: opacity 1s;
position: absolute;
}
.active2 {
opacity: 1;
z-index: 2;
position: initial;
}
<div class="mainDisplay1">
<img class="slide1 active1" src="Img1.jpg">
<img class="slide1" src="Img2.jpg">
<img class="slide1" src="Img3.jpg">
<img class="slide1" src="Img4.jpg">
</div>
<div class="mainDisplay2">
<img class="slide2 active2" src="Img5.jpg">
<img class="slide2" src="Img6.jpg">
<img class="slide2" src="Img7.jpg">
<img class="slide2" src="Img8.jpg">
</div>