Creating a Color Generator Website in JavaScript

Learn about how to create a website which will generate unique colours

Image by Paola Galimberti

This is how the final result looks like

In this tutorial we are only focusing on Javascript , you can just copy and paste the html and css from the above pen.


The UI has

  • Color Block → Created using JavaScript
  • Button → When we click the button we need to generate 10 random unique color blocks
  • Container → Color Block are appended to Container block

When the user click a button we need to

  • Generate Random Colour
  • Create a color Block
  • Make sure the colour is not already present
  • Append the color block to the container

Generating random Hex colours

We know that , hex colours has 1–9 and a-f

To generate random colours

  • Store hex values on array
  • Use math.rand to get index
  • Create a color string of length 6 or three

https://gist.github.com/Jagathishrex/13a7dab8cff2e9e904b5948bd1eaa35b#file-random_color-js

Math.random() → Generate a random number between 0 and 1 . We can multiply the random number with the length-1 of the array to get a random index.

View at Medium.com

When we call generateColor method , it will give us a random color String.

We need to make sure that the color is unique .

To store unique values we can use Set → collection of elements which does’t have duplicate values.

Learn about Set

View at Medium.com

Let’s create the set and add event listener to the button.

var set = new Set();
var btn = document.getElementById('button');
btn.addEventListener('click', function (ev) {
    // operation
});

When the user click the btn we need to generate 10 random unique colours ,for that

  • we can store the current set length in a variable size
  • Create a random color
  • Check if random color already present in the set
  • If not present in the set , then add the color to the set , create a color block and append to the container.
  • If already present in the set do nothing
  • On completion of each iteration we need to check if the set.size is less than size(old Set size)+ 10 variable
  • If the set.size is greater than size+10 than the loop will be terminated
let size = set.size; // old set Size
while(set.size < (size + 10) ) {
      let newColor = generateColor();
      if(!set.has(newColor)){
          set.add(newColor);
          // addColorBlock;
      }
}

Let’s implement addColorBlock function

function addColorBlock(color) {
   let child = document.createElement('div'),
   p = document.createElement('p');
   child.style.background = color;
   p.innerText = color.toUpperCase();
   child.append(p);
   child.classList.add("child");
   container.append(child);
}

Join your hand 🖐 with me Javascript Jeep🚙💨.

Buy me a coffee.

Buy me a coffee.

Leave a comment

Design a site like this with WordPress.com
Get started