I found the following awesome script to create a random color with javascript.
var randColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
only problem I have with this script is that it’s not garanteed that it returns a normal 7digit hex string.
sometimes it’s just 6 digits long like #e1d19.
is there a way to kind of force a 7 digit hex value?
thank you for your help.
edit: this is my actual problem:
function randColor() {
var randColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
return randColor;
}
for (var i=0; i<100; i++) {
$("#colorpicker").append("<div class='color' title="+randColor()+" style='background:"+randColor()+"'></div>");
}
I’m creating little divs with a random color, when I click on them I grab their title attribute and I’m coloring the background of my body.
however currently my code ends in
<div style="background:rgb(176, 249, 252);" title="#8bc47d" class="color"></div>
so when I grab the title attribute the color I’m giving my body is a different one than the little div shows.
You could just pad it yourself:
This trick:
is a way to get
n - 1copies of “char” in a string. I subtracted the raw length of the value from 7 instead of 6 so that when the string is 5 characters long I get one zero, when 4 I get two, etc.edit — of course (as mentioned in other answers) you can get pad zeros like this too:
I’d have to do one of those silly jsperf things to see which is faster 🙂