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

The onChange function in React JS for a Material UI 'number' TextField retains the previous value

In this element, I have an onChange function: <TextField id="rowinput" type="number" defaultValue={this.defaultRows} // defaultRows = 1 inputProps={{ min: "1", max:"5"}} onChange= ...

When the ajax response comes in, my javascript code seems to suddenly stop

After sending a POST request, my JavaScript suddenly stops working for some unknown reason. Here's the situation: I visit my webpage, fill out the form, and then click 'Click me' : Upon clicking OK in the alert popup, I see the expected ou ...

Within the materia-ui table, I am facing an issue where clicking the button to expand a row results in all rows expanding. I am seeking a solution to ensure only the selected row expands

When a row is clicked, all rows in the data table expand to show inner data for each row. The issue is that clicking the expand button expands all rows rather than just the selected row. Each time I try to expand one specific row, it ends up expanding mul ...

What could be causing my code to become unresponsive when using a for loop compared to a loop with a specific

After spending a solid 4 hours on it, I finally managed to figure it out. There were no errors popping up, so I resorted to using the debug feature which unfortunately didn't provide much insight. Without any error messages to guide me, I wasn't ...

The functionality to generate forms on the click of a button appears to be malfunctioning

I am currently attempting to dynamically create Bootstrap Panels using an `onclick` function. However, I want each Panel to generate multiple forms when the button is clicked. In my current code, the first Panel successfully creates forms when the button i ...

Examples of using React tables with Material-UI, such as the Material-UI kitchen sink demo, will showcase how to

Can someone help me figure out why the values are not visible in the react table MUI kitchen sink? When I switch to JSON, the header is visible but the data in the table disappears. Both 'data' and 'data1' have the same structure accord ...

Upon selecting the checkbox, the user will be redirected to an input textbox

Can I make it so that when I check a checkbox, it automatically directs me to a textbox as if I pressed the TAB key? Is there a way to achieve this using only HTML and CSS? ...

How can you efficiently pass the index as a prop to a child component in React.js when dealing with arrays stored in

Just starting out with React, so bear with me if my terminology is a bit off. I'm working on a table that displays a list of people in a specific order. I want to be able to assign a this.props.tablePosition value based on the index of each person. t ...

JavaScript library for creating animated car movements on a map using JPG images

Looking for a way to animate a car's movement on a map? I have a map image in jpg format (not svg) and a sequence of (x,y) points ready to go! If you could recommend a JavaScript library that can help me easily create an HTML page with this animation ...

Why are my Chrome Div regions failing to expand to their full width?

I have been searching but couldn't find an answer to my issue, so I apologize if this question has been asked before. I am working on a simple site layout and noticed that two of the div regions do not expand fully in Chrome, however, they do in Firef ...

Is there a built-in method or library for extracting data from JSON strings in programming languages?

Duplicate Query: how to parse json in javascript The data sent back by my server is in JSON format, but it doesn't follow the usual key/value pairs structure. Here's an example of the data I'm receiving: ["Value1","Value2","Value3"] ...

Can you explain how to invoke a class with express().use function?

Currently, I am delving into learning Node JS with TypeScript but have hit a roadblock with a particular issue. In my app.ts file, I have initialized the express and attempted to call the router class inside the app.use() method, only to encounter an error ...

How to apply props conditionally in VueJS?

I have a component called blogPost (Component A) that is imported in another component named B. When a button in Component B is clicked, Component A opens in a modal. There are two different use cases for this scenario. 1. One case requires passing 2 prop ...

Control the button's activation status by accepting or unaccepting the two checkbox conditions

In my search through stackoverflow for help on enabling/disabling a button conditionally, I found some assistance but nothing quite matched what I needed. My situation involves two checkbox conditions rather than just one. The button should only be enable ...

When the playback of an HTML5 Audio element is halted, the complete file undergoes downloading

Currently, I am facing a situation where a web page contains numerous Audio elements, some of which have very long durations, up to approximately two hours. To handle these audio tracks, they are created and controlled using the following code: var audio ...

Tips for repositioning a node element as the first child within its parent element

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='parent'> <div>B</div> <div>C</div> <div onload='this.parentNode.prependChild();'>A&l ...

Having trouble retrieving the chosen option from the select elements

Below is a portion of the code that I have written to capture the selected values of class code and section from a dropdown menu. Currently, only the first element of the select is being retrieved instead of the chosen element. HTML Code: <div id="dia ...

Include a parent class within the style tags in your CSS code

Currently, I am facing an issue with a web application that I am developing. On the left side of the page, there is an editable area, and on the right side, there is a live preview. The live preview area contains an HTML file with specific fields that can ...

Retrieve live data from a Python script using jQuery and PHP for immediate usage

How can I show the current temperature on a webpage? My setup involves using a Raspberry Pi 3 with the Jessie OS and Chromium as the browser. To achieve this, I have placed a Python script inside a loop for a countdown timer. The script is triggered ever ...

The server's response contained a MIME type of "application/octet-stream" that did not include JavaScript. Module scripts in HTML are subject to strict MIME type checking

Here is the structure of my project: node_modules server.js public: glsl: fragment.glsl vertex.glsl index.html main.js img.jpg style.css I have set up a simple server to serve a three.js animation in server.js const express = require('expre ...