In this article, you’ll learn how to generate random HEX colors using Javascript. Before you start with this article, first you need to know about hex code?
A hex code is a six-digit, three-byte hexadecimal number used to represent colors in HTML, CSS, etc, and other computing applications to represent colors. These bytes represent the red, green, and blue components of the color. One byte represents a number in the range 00 to FF (in hexadecimal notation), or 0 to 255 in decimal notation. This represents the least (0) to the most (255) intensity of each of the color components.
Here is an example to generate random colors using Javascript.
function random_color() {
var letters = "0123456789ABCDEF".split("");
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
You could also use jQuery to apply the random color to your element.
$('#elementId').css('color', random_color());
I hope this article will help you to understand how to generate random HEX colors using Javascript.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments