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

Navigational controls for a JavaScript slider - Backward and Forward options

I'm in the final stages of completing my slider project, but I'm stuck on how to incorporate the next() and prev() functionalities. Can anyone provide guidance on implementing these functions? http://jsfiddle.net/M4t4L/11/ $(function () { ...

Display webpage content in an Iframe using Javascript after PHP code has been executed

Despite researching keywords like PHP // Javascript // Load // URL online, I'm still struggling to fully grasp the concepts. Real-life case studies have been helpful, but I must admit that I'm feeling a bit overwhelmed at the moment. I created a ...

Utilizing CSS to create a repeating background image within a specified container

I'm currently working on setting up a container with a background image that repeats only when the contained div elements are long enough. However, I seem to be encountering issues getting the image to repeat properly within the #container code. This ...

Right-align the text in the title of the material card

Why isn't the CSS aligning my title of matcard to the right? <mat-card [ngStyle]="{ 'margin':'5px','height':'130px'}"> <mat-card-header> <mat-card-title [ngStyle]="{ 'text-align': ...

Exploring the intricacies of Jquery in Tapestry weaving

I am using jquery/datatable and I want to implement highlighting for selected rows. I found sample jQuery code that accomplishes this: var oTable; var giRedraw = false; $(document).ready(function() { /* Add a click handler to the rows - this could be use ...

to invoke a jQuery function located on a different webpage

Imagine you have two web pages: hello.html and wow.html. hello.html contains the following script: <script> $(document).ready(function() { $( "#loader" ).load( "wow.html"); }); </script> while wow.html includes this jQuery function: $(fun ...

Optimizing your approach to testing deferred always

When creating test cases for code within a jQuery AJAX call's always method or in bluebird promises' finally function, it often involves the following structure: function doStuff() { console.log('stuff done'); } function someFunct ...

What is the best way to align the navigation bar to the left using bootstrap?

I'm having trouble creating a navigation bar for my website using bootstrap 5. I tried to move the bar to the left by adding the class margin left auto (ml-auto), but it didn't work as expected. Can someone help me figure out why? Thank you in ad ...

Save the array as a variable in your JavaScript code so that you can easily access it

I am currently working on generating a list only when a specific page is visited using JS/jQuery. I then need to be able to access this list when navigating to other pages and retrieve the variables within it. How can I effectively store this list? Initia ...

The issue with Angular's mat-icon not displaying SVGs masked is currently being investigated

I have a collection of .svgs that I exported from Sketch (refer to the sample below). These icons are registered in the MatIconRegistry and displayed using the mat-icon component. However, I've observed issues with icons that utilize masks in Sketch ...

How is the CSS selector affected by the presence of an asterisk (*)?

Take for instance the following code snippet: (I am familiar with using a star in CSS selectors, but not with '> *') .row > * { float: right; } And then there's this one: .row.uniform > * > :first-child { mar ...

Troubleshooting Bootstrap 4 problem with varying sizes of div content

I have encountered a problem with the script below, where the content in a div is of variable size and does not always occupy the entire horizontal space allotted by the col-6 class from one row to the next: <div class="card-body " > <div c ...

Placing an Image in the Right Corner Using jQuery Mobile

I am currently developing a mobile app and I need to align three images one below the other at the right corner next to some text. Any suggestions would be greatly appreciated. Thank you in advance. Below is my code snippet: <div> <ul data-r ...

Implementing the Facebook like button using JavaScript with XML and XFBML

Describing the issue at hand: Whenever I try to load a Facebook XML tag (shown below) on a page loaded with Ajax, it does not display properly. The table2.php page is supposed to be loaded by Ajax within the following div: <div id="update_div">< ...

The vertical scrolling issue arises when the content exceeds the height of the screen

Seeking a solution to enable scrolling of users within a flexbox menu, I've come across an interesting discovery. When setting a specific height in pixels for my nav element (like 100px), everything works perfectly. However, when I set the height to 1 ...

Trigger Knockout bindings once the ajax request has been completed

In the view, I have the following script: <script> MyObj.initModel(getUrl); $(document).ready(function () { ko.applyBindings(MyObj.viewModel, document.getElementById("someId")); ...

Electron employee: Concealed BrowserWindow leads to delay in the interface

My worker runs in a hidden browser window and sends multiple requests simultaneously. However, these requests from the worker end up causing lag and freezes in the main browser window. Any suggestions for resolving this issue? ...

unique close button design for pop-up video player on YouTube

Struggling to add a custom close button to my Youtube video pop up. After unsuccessful research attempts, I'm turning to my fellow stack buddies for help. Any suggestions? ...

showing console logs before initializing preferences may lead to inaccurate results

My Content Management System (CMS) is WordPress. Recently, after making some changes, I encountered an error on a specific page: An error occurred: loading pref showConsoleLogs before prefs were initialised, leading to incorrect results being displayed - ...

conceal the offspring from the guardians, not the offspring

Could you please assist me with this situation... <li id="4331">Region <ul> <li id="4332">Asia</li> <li id="6621">Europe</li> </ul> </li> I have a query when I click on the Reg ...