Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

245
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda