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.