Get Random Color using JavaScript

Returning random colors is quite simple. You just need to create a JavaScript function that returns a color. We will look into two different methods to get random color using JavaScript; in HEX and in RGB.

See it in Action?

Random HEX Color in JS

Just create a function that uses the Math.random method with a number that represents HEX white: ffffff in decimal: 16777215. Then pass that number to a string with a parameter that will return a hexadecimal value: 16. Finally, use a Math.floor method to make sure we only get integers!

function random_hex(){
    return '#' + Math.floor(Math.random()*16777215).toString(16);
}

Random RGB Color in JS

Just create a function that uses the Math.random method with a number that represents RGB white (255, 255, 255). Use a Math.floor method to make sure we only get integers!

function random_rgb(){
    return 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
}

This is also possible in PHP. See PHP version

Source #1: Random Hex Color Code Generator in JavaScript
Source #2: Generating Random Color Values using JavaScript

Post a Comment

To post code, use the code tag with a class language-*
Examples: code class="language-markup"code class="language-css"