JavaScript to generate random hex codes of color
What is hex code?
A hex code is a six-digit, three-byte hexadecimal number used to represent colors in HTML, CSS, SVG. The 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.
Functions to be used for generating hex codes:
Math.random() generates any no. between 0 and 1 including decimal.
Math.random() * 16 generates no. between 0 to 16 including decimal.
Math.floor() removes the decimal part.
<script> // storing all letter and digit combinations // for html color code var letters = "0123456789ABCDEF" ; // html color code starts with # var color = '#' ; // generating 6 times as HTML color code consist // of 6 letter or digits for ( var i = 0; i < 6; i++) color += letters[(Math.floor(Math.random() * 16))]; document.write(color); </script> |
Output:
#E3B0DF
Note: Output will be different for everytime the code will get executed.
Reference: https://en.wikipedia.org/wiki/Web_colors#Hex_triplet
Recommended Posts:
- How to generate a random boolean using JavaScript ?
- How to pick a random color from an array using CSS and JavaScript ?
- How to generate random number in given range using JavaScript?
- Generate random alpha-numeric string in JavaScript
- How to change text color depending on background color using JavaScript?
- Understanding basic JavaScript codes.
- JavaScript | Random
- JavaScript | Math.random() function
- How to select a random element from array in JavaScript ?
- JavaScript | Check if a string is a valid hex color representation
- How to change the background color after clicking the button in JavaScript ?
- JavaScript | Program to generate one-time password (OTP)
- How to change an element color based on value of the color picker value using onclick?
- How to get hex color value of RGB value ?
- p5.js | random() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.