The image slide change feature ceases to function properly when incorporating two separate functions

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>

Answer №1

To ensure the proper functionality of your code, make sure to retrieve the node list every time you call the function and keep your index variables separate to avoid incrementing them unintentionally. Additionally, be cautious when adding multiple functions to the window.onload event as the latest one will overwrite any previous ones.

let index1 = 0;
let index2 = 0;

function change1() {
  const slides1 = document.querySelectorAll(".mainDisplay1 .slide1");

  if (++index1 >= slides1.length)
    index1 = 0;

  for (let i = 0; i < slides1.length; i++)
    slides1[i].classList.toggle("active1", i == index1);
}


function change2() {
  const slides2 = document.querySelectorAll(".mainDisplay2 .slide2");

  if (++index2 >= slides2.length)
    index2 = 0;

  for (let i = 0; i < slides2.length; i++)
    slides2[i].classList.toggle("active2", i == index2);
}


window.onload = function() {
  setInterval(change1, 5000);
  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="https://via.placeholder.com/250?text=Img1">
  <img class="slide1" src="https://via.placeholder.com/250?text=Img2">
  <img class="slide1" src="https://via.placeholder.com/250?text=Img3">
  <img class="slide1" src="https://via.placeholder.com/250?text=Img4">
</div>

<div class="mainDisplay2">
  <img class="slide2 active2" src="https://via.placeholder.com/250?text=Img5">
  <img class="slide2" src="https://via.placeholder.com/250?text=Img6">
  <img class="slide2" src="https://via.placeholder.com/250?text=Img7">
  <img class="slide2" src="https://via.placeholder.com/250?text=Img8">
</div>

Answer №2

One way to ensure your onload functions are executed properly is by using the following method:

window.onload = function() {
  setInterval(function() {
    runFunction1();
    runFunction2();
  }, 5000);
}

Keep in mind that calling onload multiple times will not work as expected.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Only send the parameter for variables that are not empty in the AJAX data

How can I pass the variables that are not empty in the data object for an AJAX request? In this scenario, the area variable is empty so I need to pass parameters for city and listing type instead. Can someone please help me figure out how to do this? va ...

Optimize HTML outputs in Smarty by reducing the file size

Is there a way to minify all output HTML templates in Smarty automatically? Would it be possible to set something like this: $smarty->minify = true; Additionally, I have come across the {strip} function but using it in every single .tpl file is not fe ...

Creating a Personalized Dropdown Menu Within the <div> Tag

My current task involves obtaining an element in the following format: https://i.sstatic.net/uhHkL.png Inside the nav-item, there is a dropdown with a top-centered triangle on it, and the dropdown is positioned at the center. Below is what I have achiev ...

What causes the JavaScript code to output the number 3?

What is the reason behind the output a == 3 in this code snippet? var x = "abc"; var y = 3; var z = "xyz"; var a = x && y || z; Here is the link to interact with the code: http://jsfiddle.net/thinkingmedia/qBZAL/ One might assume that a == true ...

Align an image in the middle with a heading

I am currently working on aligning a picture and heading in a header section. My goal is to center both elements, with the picture being twice as tall as the heading. So far, I have them stacked one above the other: .body { font: 15px/1.5 Arial, Helveti ...

Using Selenium Webdrivers to Browse Pages with Minimal Resource Loading

I'm attempting to restrict Javascript from altering the source code of the site while testing with Selenium. Disabling Javascript completely in the Webdriver is not an option as I require it for testing purposes. Below is my approach for the Firefox W ...

What causes the modal to appear and then vanish suddenly?

I've created a simple modal code with minimal JS involved. When the button is clicked, the modal appears briefly, then the page refreshes and the modal disappears. I'm not sure what could be causing this issue. Any help would be appreciated! h ...

Is there a way to automatically refresh a page as soon as it is accessed?

My goal is to create a page refresh effect (similar to pressing Command+R on Mac OS) when navigating to a certain page. For instance: Currently, when I navigate from "abc.com/login" to "abc.com/dashboard" after successfully logging in, the transition occ ...

The specified type '{ children: Element; ref: MutableRefObject<HTMLDivElement>; }' cannot be matched with type 'IntrinsicAttributes & RefAttributes<HTMLDivElement>' in the assignment

Encountering an issue with fowardRef in ReactJS where everything seems fine, but an error pops up: Type '{ children: Element; ref: MutableRefObject<HTMLDivElement>; }' is not assignable to type 'IntrinsicAttributes & SectionContent ...

Encountering difficulty retrieving the value of a hidden input with jQuery's find method

When a user clicks on the delete icon, I want to retrieve the value of the hidden input inside the "delete" class. However, I am getting an undefined result. Can someone please guide me on where I might be going wrong? <table class="items-list"> ...

Tips on adjusting the dimensions of a switch in kendo UI angular with CSS

Currently, I am utilizing angular in combination with Kendo ui. Is there a way to modify the dimensions of the switch button in Kendo UI Angular using CSS? ...

What is the method used by three.js to render video with spherical UV mapping?

I have a streaming video displayed in a 3*3 format. I am able to splice the entire video into individual sections using THREE, // Creating a 3x3 PlaneGeometry var geometry = new THREE.PlaneGeometry(400, 200, 3, 3); const video1 = document.getElem ...

When attempting to redirect to a different page using setTimeout, the loading process appears to continue indefinitely

Currently, I am utilizing the following script: setTimeout(function(){ window.location.href = '/MyPage'; }, 5000); While this script successfully redirects me to /MyPage, it continuously reloads every 5 seconds. Is there a way to r ...

Having difficulties updating a value in Angular through a function written in HTML- it refuses to update

<select ng-model="currentTimeStartHour" style="width: 33%" ng-change="UpdateTime(this)"> <option ng-repeat="hour in choices" value="{{hour.id}}">{{hour.name}}</option> </select> Somewhere else on the page... {{totalHours}} Whe ...

Creating custom validation in Vuetify for password confirmation is essential in ensuring that

While developing a Vue.js template, I encountered a scenario on the sign-up page where I needed to compare passwords during user registration. To achieve this, I implemented a custom validation rule in the code snippet below: <v-text-field label=" ...

Importing models in SceneJS does not function properly with Internet Explorer

I've been exploring different webGL frameworks lately. While I like SceneJS, I've noticed some compatibility issues with Internet Explorer. For instance, in IE 11, importing OBJ files seems to cause the online examples to freeze up: Check out th ...

Here's the step-by-step process: Access the specific item in the object by referencing `obj[i]["name of desired attribute"]

I tried seeking advice and consulting multiple sources but none provided a suitable answer. Is there someone out there who can assist me? obj[i].["name of thing in object"] Here's the array: [ { "name": "DISBOARD#2760" ...

Unveiling all Gatsby.js routes/endpoints in Cypress tests: A comprehensive guide

I am currently in the process of creating end-to-end tests with Cypress for a project built on Gatsby. One specific test requires me to iterate through all pages of my Gatsby site. To accomplish this, I require a test fixture (such as endpoints.json) cont ...

Bootstrap does not show submenus on its navigation menus

I am currently designing a menu with Bootstrap, but for some reason, the submenu items are not showing up. https://i.stack.imgur.com/qZqyf.png After carefully reviewing the HTML code multiple times, I am unable to identify any issues. I am now questionin ...

Ion-row appears out of frame

This is a simple layout: <ion-content> <ion-grid *ngIf="loaded"> <ion-row> <ion-col>Stuff</ion-col> <ion-col>Stuff</ion-col> <ion-col>Stuff</ion-col> </ion-row> < ...