Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

234
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda