Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a random background color in javascript

Tags:

javascript

I am new to java-script . I need to get a random background color whenever i call a particular function.

I found the following code on the web but i don't quite understand how it works.

Code:

function getRandomColor () {
  var hex = Math.floor(Math.random() * 0xFFFFFF);
  return "#" + ("000000" + hex.toString(16)).substr(-6);
}

How is the above code working.I understand how Math.random() works but what does hex.toString(16)).substr(-6) basically signify?

Can some one please clarify it to me how the above code works.

like image 405
poorvank Avatar asked Sep 16 '13 05:09

poorvank


3 Answers

function getRandomColor () {
  var hex = Math.floor(Math.random() * 0xFFFFFF);
  return "#" + ("000000" + hex.toString(16)).substr(-6);
}

hex.toString(16) converts hex into string number representation in base 16.

Syntax:

number.toString(radix)

radix: Base to use for representing a numeric value. Must be an integer between 2 and 36.

2 - The number will show as a binary value
8 - The number will show as an octal value
16 - The number will show as an hexadecimal value

substr(-6) just takes the last 6 characters, which cuts off the "000000" because they're not part of the last 6 characters.

like image 84
Kiran Avatar answered Nov 16 '22 22:11

Kiran


hex.toString(16) converts hex into string number representation in base 16. Then it appends 000000 at the beginning of the string to make sure it will be at least of length 6. and substr(-6) takes last 6 chars of the resulting string. This way you always get # + 6 hex chars. Which represents color.

like image 34
zaquest Avatar answered Nov 16 '22 22:11

zaquest


The code first picks a random number and using the "& 0xFFFFFF" technique it ensures the range is something like 0 to 16777215.

Once we have that random number we convert to hexadecimal using the ".toString(16)" method, the 16 signifying we want hexadecimal conversion.

Now, we can think we have a 6 digit random number in hex to use for our color but know that the ".toString(16)" method does not do any padding for us.

For example, if the random number is 255 which is FF in hex, is not usable as it since it is not precisely 6 digits long.

One technique is to do a string length check and add the corresponding number of 0's to the beginning of the 'FF' to get '0000FF'.

Here we see another technique where you see a fixed number of 0's added to the string and then a fixed length is chopped of the end, ensuring you get 6 digits and correctly padded.

I've always used the string length check or specific padding functions (I don't know if javascript has one) - I only answered the question so as to fully appreciate the technique shown in this question.

like image 36
zaf Avatar answered Nov 16 '22 21:11

zaf