I have a site where I have 5 columns 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 columns remain the same as before. I’ve put an alert to check if “colors[i]” change, and it does. So why do some columns remain the same in some iteration and in others don’t?
Please note that every column has the “.colorcolumn” class.
function calculation() { $(".colorcolumn").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(); } })
Advertisement
Answer
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') }