Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
jQuery's .css method works differently inside and outside of the loop

Disclaimer: I am not a front-end engineer, and never was. So, I apologise if I'm missing something very obvious, but I can't wrap my head around whatever I have just experimented in the JavaScript and jQuery.

In my HTML document, I have some div elements, a button element, and a <script> containing:

$("button").click(function(){

    $("div").fadeOut();
    var colour = "rgb(" + Math.floor(Math.random()*255) + ", " + Math.floor(Math.random()*255) + ", " + Math.floor(Math.random()*255) + ")"
    $("div").css("background-color", colour);
    $("div").fadeIn(100);

});

and this works as expected. Each and every new click on the <button> changes background colour of all the div elements, in the enclosing HTML document, setting them to randomly generated RGB values.

If I, however, want to play a little bit and make some "colourful show", by putting all this snippet in a loop, as:

$("button").click(function(){

    for (var i = 0; i < 10; i++) {
        $("div").fadeOut();
        var colour = "rgb(" + Math.floor(Math.random()*255) + ", " + Math.floor(Math.random()*255) + ", " + Math.floor(Math.random()*255) + ")"
        console.log(colour);
        $("div").css("background-color", colour);
        $("div").fadeIn(100);
    }
    
});

all the iterations fade out and fade in with the same colour, although, I expect them to be random, and even console.log(colour) prints different (random) values.

Note, that I understand, that random can be a pseudo-random, relying on the default seed, but this doesn't matter here.. my problem is having discrete values, in colour variable, but not having them worked, as expected, in the .css method.

So, why does this (probably - .css?) work differently inside and outside of loop?

I am using Google's Chrome, if that matters.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!