DEV Community

Cover image for Build a Random Hex Color Generator with Vanilla JavaScript
Toluwanimi Isaiah
Toluwanimi Isaiah

Posted on

Build a Random Hex Color Generator with Vanilla JavaScript

In this tutorial, I will be showing how I built a hex color generator. It is a simple page that generates a random hexadecimal color code when you click a button and updates the background of the page to correspond with the generated color code.

The markup

I decided to make the page very simple, giving it only a heading containing a span tag that will display the value of the current background color, and a button.

<body>
  <div class="container">
    <h1>Hex Color: <span class="hexValue">#ffffff</span></h1>
    <button id="btn">Click to generate new color</button>
  </div>
</body>
Enter fullscreen mode Exit fullscreen mode

Styles

I gave the page a default background color of white, added a transition effect to make the color change smoother and set its height and width to that of the viewport which is the user's visible area of a web page. Then I went ahead to center the contents of the page using CSS Flexbox:

body {
  background: #ffffff;
  font-family: 'Lato', sans-serif;
  transition: background 0.3s;
}

.container {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  letter-spacing: 0.1em;
}
Enter fullscreen mode Exit fullscreen mode

Functionality

First thing I did was to create references to the necessary HTML elements and the button in the JS file.

const button = document.querySelector('#btn');
const body = document.querySelector('body');
const value = document.querySelector('.hexValue');
Enter fullscreen mode Exit fullscreen mode

Then I stored all hexadecimal values in an array and added a click event listener to the button:

const hexValues = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F']; 

button.addEventListener('click', changeHex);
Enter fullscreen mode Exit fullscreen mode

I defined the callback function of the event listener as follows:

function changeHex() {
  let hex = '#';

  for(let i = 0; i < 6; i++){
    const index = Math.floor(Math.random() * hexValues.length)
    hex += hexValues[index];
  }

  value.textContent = hex;
  body.style.backgroundColor = hex;
}
Enter fullscreen mode Exit fullscreen mode

Every time the button is clicked, the changeHex function is called which creates a variable hex and sets its value to #. Then it loops over the hexValues array 6 times and each time generates a random number using Math.random().

Now, the Math.random() function picks a random number between 0 and 1 (not including 1) and returns a decimal but we don't want decimals. So what do we do if we want a whole number larger than 1? We multiply it by the number we want (in this case, the length of the hexValues array) and wrap it within the Math.floor() function which returns the largest integer less than or equal to a given number. It basically rounds it down to the nearest whole number. This makes sure that any number generated is a valid hexValues index.

The random whole number generated is appended to a new variable index. I can now access the hexValues array item in the position corresponding to the generated index number using bracket notation, then add it to the end of the hex variable i.e hex += hexValues[index]. Then the cycle repeats itself until the 6th round is over at which time a full 6-digit hex code will have been generated.

Updating the page

All that's left is to set the textContent of the span tag and the background color of the page to be the value of hex. And that's all!

Conclusion

We've successfully built a random hex color generator using HTML, CSS and a few lines of JavaScript. I hope you learnt a lot from my method. You can find the complete code on my GitHub repository. There are certainly other ways to achieve the same result so do check them out and give them a try.

Thanks a lot for reading, and happy coding!

Top comments (9)

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

Awesome job on the project!

Did you know you can input hex directly using 0x... notation, and write it to a string using Number#toString(16)? So you can simplify your random number generation something like this:

const color = '#' + Math.floor(Math.random() * (0xffffff + 1))
    .toString(16)
    .padStart(6, '0') // in case the number is too small to fill 6 hex digits
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited
const color = '#'+(~~(Math.random()*2**24)).toString(16).padStart(6,0)

const color = `rgb(${[0,0,0].map(_=>~~(Math.random()*256)).join()})`

const color = '#000'.replace(/0/g,x=>(~~(Math.random()*256)).toString(16).padStart(2,0))

const color = `rgb(${'0,0,0'.replace(/0/g,x=>~~(Math.random()*256))})`

const color = `rgb(${Array.from('   ',Math.random).map(x=>~~(x*256)).join()})`

// randomness might not be so good on this one
const color = '#'+[...'0123456789abcdef'.repeat(3)].sort(a=>-.5+Math.random()).join('').slice(-6)
Enter fullscreen mode Exit fullscreen mode

😁

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

The first one won't produce any colors with red in them — 2 ** 16 is 0x10000, whereas the size of the full RGB color space is 0x1000000 (2 ** 24) 😉

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Yup, typo. Cheers

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Another:

const color = [..._='facedb'].reduce(x=>x+(_+0x3d00b615)[~~(Math.random()*16)],'#')
Enter fullscreen mode Exit fullscreen mode
Collapse
 
barman47 profile image
Uzoanya Dominic

Really nice. I did something similar on a project I worked on except the users aren't really aware of what's going on. With your permission I'd like to turn this into a video tutorial and give due credit.

Collapse
 
toluagboola profile image
Toluwanimi Isaiah

Sure, that'll be great. Go ahead!

Collapse
 
barman47 profile image
Uzoanya Dominic

Thank you!

Collapse
 
buriti97 profile image
buridev

very nice