Home > OS >  .each not always change values?
.each not always change values?

Time:09-11

I have a site where I have 5 colomn and I want to change their background with some random colors. I don't get why sometimes it changes it, sometimes it doesn't and some coloumn remain the same as before. I've put an alert to check if "colors[i]" change, and it does. So why does some colomn remain the same in some iteration and in others don't? Please note that every colomn has the ".colorcoloumn" class.

function calculation() {
    $(".colorcoloumn").each(function(i) {
        let hexrandomCol = randomColor();
        colors[i] = hexrandomCol;
        $(this).css("background-color", colors[i]);
    }
)}
//generate a random color
function randomColor() {
    let color = "#";
    while (color.length < 7) {
        color  = Math.floor(Math.random() * 256).toString(16);
    }
    return color;
}

//change colors on spacebar press
$("body").keyup(function (e) {
    if (e.keyCode == 32) {
        $(".save-palette").text("Save Palette");
        calculation(); 

    }
})

CodePudding user response:

The issue is likely because you sometimes create invalid colors with 7 digits instead of 6 because you don't pad the string to two digits if its value was less than 0x10. Setting such an invalid CSS property value will be simply ignored.

On that note, you could probably simplify that whole thing as follows:

function randomColor () {
  return '#'   Math.floor(Math.random() * 0x1000000)
    .toString(16)
    .padStart(6, '0')
}
  • Related