Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript random color with 7digits must

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.

like image 486
matt Avatar asked Jun 26 '26 07:06

matt


2 Answers

You could just pad it yourself:

function randomColor() {
  var rc = (~~(Math.random() * 0xFFFFFF)).toString(16);
  return '#' + new Array(7 - rc.length).join('0') + rc;
}

This trick:

new Array(n).join(char)

is a way to get n - 1 copies 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:

  return '#' + "000000".slice(rc.length) + rc;

I'd have to do one of those silly jsperf things to see which is faster :-)

like image 126
Pointy Avatar answered Jun 30 '26 04:06

Pointy


var randColor = '#'+(0xFFFFFFFF-Math.random()*0xFFFFFFFF).toString(16).substr(0, 6);
like image 45
Lex Avatar answered Jun 30 '26 03:06

Lex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!