Loop through an array of div IDs and update their CSS styles individually

How can I iterate through an array of Div IDs and change their CSS (background color) one after the other instead of all at once? I have tried looping through the array, but the CSS is applied simultaneously to all the divs. Any tips on how to delay the effect so that each div changes its color sequentially would be greatly appreciated.


$("#light").click(function(){
    for (var i=0; i < randomArray.length; i++) {
        $("#" + randomArray[i]).css("backgroundColor", "Black"); //Is there a way to change the colors one by one instead of all together?//
    }
});

Answer №1

If you want a cleaner and faster solution, consider using CSS animation delays.

var elements = ["elem1", "elem2", "elem3"];

$("#light").click(function(){

     for (var i=0; i < elements.length; i++) {

         $("#" + elements[i]).addClass("fade-"+i);

     }
});

You now have classes like fade-1, fade-2, fade-3 to work with.

In your CSS file:

.fade-0,.fade-1,.fade-2{
   background-color: black;
   transition: background-color 1s;
}
.fade-1{
   transition-delay: 1s;
}
.fade-2{
   transition-delay: 2s;
}

Answer №2

experiment with this code snippet


let count = 0;
$("#button").click(function(){
      adjustStyle(count);
})
function adjustStyle(number){
if(count < array.length){
     $("#" + array[number]).css("color", "Red");
      count++;
         setTimeout(function(){adjustStyle(count)},1500) 
} 
}

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

Creating a functional component in React using TypeScript with an explicit function return type

const App: FC = () => { const addItem = () => { useState([...items, {id:1,name:'something']) } return <div>hello</div> } The linter is showing an error in my App.tsx file. warning There is a missing return type ...

Tips for sending variable from JavaScript to PHP Page through XMLHTTP

Make sure to review the description before flagging it as a duplicate. In my understanding, the method of transmitting data from JavaScript to PHP is through Ajax Call. This is the situation I am facing: With PHP, I bring forth an HTML page that cont ...

Switching from using jQuery.ajax() to fetch() when making requests to a Go REST API endpoint with no payload

I have a ReactJS web application that communicates with a REST API endpoint built in golang. Previously, I used jQuery to make Ajax POST requests and it worked perfectly. Here's an example of the code: // Using jQuery let sendUrl = "http://192.168.1 ...

Discover the power of utilizing JavaScript to sort through table rows by filtering them based on the selections of multiple checkbox

How can I create interdependent logic for checkbox sections in a form to filter based on all selections? I am looking for help with my code snippet that showcases checkboxes controlling the visibility of table rows: $(document).ready(function() { $(" ...

Why is the React onClick method returning undefined upon the first selection, and why are the values being passed not consistent with

While attempting to create a list of users that, when clicked, should open up a corresponding user's message, I encountered an issue where clicking for the first time resulted in an 'undefined' value being passed. I've tried troublesho ...

Creating a responsive table layout with CSS

I currently have the following code: .fiftyFiftySection { background-color: #000; } .odometer { font-size: 3em; text-align: center; } table td { column-width: 1000px; text-align: center; } @media (max-width: 500px) { table td { column ...

Appium with Node.js (wd) becomes unresponsive when unable to locate element

Encountering an issue while using appium with nodejs (wd) and mocha, as there is a loading view in the android app (blackbox testing & I'm not the developer) that needs to be waited for its disappearance. Attempted the following solution: wd.addPromi ...

Using PHP and jQuery to generate push notifications can result in issues with server performance

To simulate push notifications using PHP, I have implemented the following method: An AJAX call is made to a server-side script using jQuery. The script includes a for loop with a sleep function after each iteration to introduce delay. If a certain condi ...

Tips for transferring an array variable into a div element using AJAX

I have a div like the following: <div id="#myid"> if($values){ echo "<p>$values['one']</p>"; echo "<p>$values['two']</p>"; } </div> Due to the large size of my div, I want to make a request ...

Ways to resolve the issue with TypeError: CSS2Properties lacking an index property setter for '0'

I'm currently working on application development using ReactJs and Material UI. When I try to open the application in Mozilla Firefox, an error message pops up saying "TypeError: CSS2Properties doesn't have an indexed property setter for ' ...

Steps for customizing the dropdown arrow background color in react-native-material-dropdown-v2-fixed

Currently, I am utilizing react-native-material-dropdown-v2-fixed and I am looking to modify the background color of the dropdown arrow. Is there a way for me to change its color? It is currently displaying as dark gray. https://i.stack.imgur.com/JKy97.pn ...

Unable to make changes to the data

Journey Route::resource('/videofile', 'VideoController'); VideoController public function update(Request $req, $id){ $video = Video::findOrFail($id); if($req->hasFile('UserVideo')){ $vid = $req->file(& ...

"Troubleshooting: How to Fix Issues with document.getElementById on Dynamic Div

Struggling to incorporate div elements and generate graphs with Google charts? The issue arises in the draw function, where attempts to access a div element using document.getElementById() result in null values and an error message stating "container not ...

Sort through a list of objects using the criteria from a separate array

Looking to apply a filter on an array of objects: const myArray = [{ id: 4, filters: ["Norway", "Sweden"] }, { id: 2, filters :["Norway", "Sweden"] }, { id: 3, filters:["Denmark", "Sweden&q ...

The combination of Material UI custom TextField and Yup does not seem to be functioning properly

I am facing an issue with integrating my custom TextField into my RegisterForm along with Yup validation. Whenever I use the custom TextField, I encounter a message "⚠ Champ obligatoire" after clicking on Submit, which is not the case when using a simple ...

Consistently Encountering The 404 Error

Greetings! Below is the code snippet from my app.js: var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require(& ...

Modifying the page header content using JavaScript

There's this snippet of code that alters the image on another page: <div class="imgbx"> <button onclick="window.location.href='index.html?image=images/xr-black.jpg&tit=XR-black'" >Invisible ...

Loading animation reminiscent of a whirlpool, similar to the movement

In my quest for the perfect animation, I have scoured far and wide. Unfortunately, the one I found at http://jsfiddle.net/pedox/yed68/embedded/result/ is created using css, which many browsers do not yet support fully. I also explored , but found it to be ...

Is there a way to verify if the JSON Object array includes the specified value in an array?

I am working with JSON data that contains categories and an array of main categories. categories = [ {catValue:1, catName: 'Arts, crafts, and collectibles'}, {catValue:2, catName: 'Baby'}, {catValue:3, catName: 'Beauty ...

Getting the value of a JavaScript variable and storing it in a Python variable within a Python-CGI script

Is there a way to capture the value of a JavaScript variable and store it in a Python variable? I have a Python-CGI script that generates a selection box where the user can choose an option from a list. I want to then take this selected value and save it ...