How to Generate Random Colors in JavaScript?

Random is an action that happens without order or reason. In some cases we need random values. JavaScript provides a function for generating random values

i.e.
Math.random()
The random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).

In our case we need six digit random hexadecimal color. i.e #FF0000 represent the "RED" color. Read more about Hex colors.
For example in dynamic pie or bar chart view, we need random colors. Here we explain how to generate random colors in javascript.

function GetRandomHexColor()
{
    var AllowedLetters = '0123456789ABCDEF';
    var Color = '#';
    for (var i = 0; i < 6; i++ )
    {
        Color += AllowedLetters[Math.floor(Math.random() * 16)];
    }
    return Color;
}
A demo for changing the border color and text color of a div by using JQuery.


Demo

No comments:

Post a Comment