The formula is incorrect. here is a corrected version:
var x=Math.round(0xffffff * Math.random()).toString(16);
var y=(6-x.length);
var z=”000000″;
var z1 = z.substring(0,y);
var color= “#” + z1 + x;
This way if the length of the Hex number is too short, the appropriate number of zeros are added to the beginning and you don’t get any illegal values for color.
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
Even better would be to incorporate transitions/transforms and you could have constantly changing background colours purely done within CSS – no script necessary!
Sometimes script make wrong string, 5 chars only.
This should fix this problem, (it is also more readable).
‘#’+(Math.random()*0xFFFFFF<<0).toString(16);
The formula is incorrect. here is a corrected version:
var x=Math.round(0xffffff * Math.random()).toString(16);
var y=(6-x.length);
var z=”000000″;
var z1 = z.substring(0,y);
var color= “#” + z1 + x;
This way if the length of the Hex number is too short, the appropriate number of zeros are added to the beginning and you don’t get any illegal values for color.
Hi all sorry to be dense but how do I integrate this into CSS code as the example has done?
Many thanks,
Andrew.
felt inspired for something small but fun.
A function you could use is this:
There is a preview of it here, just click the button:
http://sweb1.dmit.nait.ca/~bkoepke1/Random%20Colour%20Generator/
because you using floor , you will never get the last value of FFFFFF
Math.random()*16777215
How could I use this function to set a value in my CSS file?
I created a a file called randomcolor.js
var @randomColor = Math.floor(Math.random()*16777215).toString(16);
and then in my variables.less file I tried
@adjacent-color: ‘#’ + @randomColor
I also just tried doing
@adjacent-color: โ#โ+(Math.random()*0xFFFFFF<<0).toString(16);
But you’re doing it with script. This is “CSS-tricks.com”, right? Not Javascript tricks or PHP tricks!
What I want to know is, how can you put the random number into the CSS file?
eg:
{
font-family:sans-serif;
font-size:2em;
color: white;
background-color: (random number generator here);
}
Even better would be to incorporate transitions/transforms and you could have constantly changing background colours purely done within CSS – no script necessary!