Yogesh Chauhan's Blog

How to create a Random Hex Color generator using JavaScript?

in JavaScript on March 26, 2021

Elements setup using HTML and CSS

Let’s start with the basic HTML elements and styling those elements.

Let’s add a span element with an ID that will be used to change the HEX color code in it. Initially we can set any HEX color. I have set it as #bbbbbb.

Also, using CSS I have set the same background-color so that we can visually see how the HEX color code looks like every time we get the random one.

There are two few ways to change the HEX code and background-color for the span. We can either use setInterval and that will keep refreshing it for us periodically or we can just add a button to get the click from the user and show the color until user clicks on the button and ask for a different color.

Let’s go with the second method since it will give user a chance yo copy the color if they like it.

Looks much better now. I have added a bit style for the button with wrapping the span tag with a p tag to create a nice gap between the elements.

JavaScript function

Let’s add the JavaScript function now. But before that let’s understand the different things we need to make the complete function.

The color numbers start at 0(Black color) and end at 16,777,215(White color). That’s equal to a total of 16,777,216 unique colors.

What we are going to do is make a random HEX color using Math.random() method and total number of colors. After that we can just round the random number we get using Math.floor() method. Finally, we can using toString() method to convert the number into a string.

That’s it. You have your personal HEX code generator.

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Quick Introduction to 11 Array Iteration Methods in JavaScriptJavaScriptList of WordPress directories functionsWordPressWhat are “holes” in a React component?ReactThe basics of @import rule in SCSS (Sass)SCSSForcing the domain to serve securely using HTTPSMiscellaneousRelative Length Units in CSSCSS