How to Build a Random Color Flipper with Vallina Javascript

timonwa

Timonwa Akintokun

Posted on April 5, 2022

How to Build a Random Color Flipper with Vallina Javascript

Hi guys and welcome to the second article in my Javascript Project Series, a series where I will be building 10+ Javascript projects, to test and build our Javascript coding skills.

In this second article, we going to learn how to build a Color Flipper using JavaScript. In case you don't know what a Color Flipper is, it is just a simple random color generator that changes the background of a web element to that random color, at the click of a button.

Note: All codes for each project in the series can be found on my GitHub and the deployed link to view all the projects is here.

Prerequisites

I am going to assume that you are already familiar with using Html, CSS, and JavaScript and also have a basic understanding of how JavaScript DOM Manipulation works.

We will also be using Math.Random() and Math.Floor() functions to generate the random color values.

And with that on the confirmation,

gif of a lady saying let's get started

What is a Color Flipper?

Like I said earlier, a Color Flipper is a fun mini javascript project where you create a simple button, that on click, runs a function that generates a random color and then sets the background/color of an element you preselected to that random color.

For this project, we are targeting the background color of our body element and changing it using 3 different color codes; hex, rgb, and hsl. We are also going to use the Math.random() function combined with the Math.floor() function in Javascript to randomly generate the colors.

Building the Color Flipper

To build this we first need to open our code editor and create 3 files called index.html, style.css, and script.js.

Adding Html

In our index.html file, write the following code:

<!-- header -->
<header>
  <div class="page-header">
    <h1>Color Flipper</h1>

    <div class="page-links">
      <span id="hex-page">HEX</span>
      <span id="rgb-page">RGB</span>
      <span id="hsl-page">HSL</span>
    </div>
  </div>
</header>

<!--* body -->
<main>
  <section class="main-wrapper" id="hex-wrapper">
    <p>Change the background color by clicking this button.</p>
    <button id="hex-color">#babfff</button>
  </section>

  <section class="main-wrapper" id="rgb-wrapper">
    <p>Change the background color by clicking this button.</p>
    <button id="rgb-color">rgb(120, 191, 255)</button>
  </section>

  <section class="main-wrapper" id="hsl-wrapper">
    <p>Change the background color by clicking this button.</p>
    <button id="hsl-color">hsl(26, 100%, 86%)</button>
  </section>
</main>

Enter fullscreen mode Exit fullscreen mode

In our Html file we have created a simple header that says Color Flipper and a div that contains 3 links called HEX, RGB, and HSL. We also created 3 sections in our main tag that contains a paragraph and a button that on click will change the background of our body element.

At the moment, all 3 sections are visible, when we add our CSS styles to them, only one will be visible at a time. And with Javascript, we will use our links to toggle on and off the visibility of each section corresponding to that particular link. We will also be able to change the background color of our page with the click of the button in that section.

Adding CSS

So let's now add our CSS:

/** body */
body {
  background-color: #babfff;
  padding: 20px;
}

/** header */
header {
  width: 100%;
  margin: 20px 0;
  text-align: center;
}

/** page links */
.page-links > span {
  font-weight: bold;
  cursor: pointer;
}

/* first-page link */
#hex-page {
  text-decoration: underline;
}

/* second and third-page links */
#rgb-wrapper,
#hsl-wrapper {
  display: none;
}

/** main */
.main-wrapper {
  width: 300px;
  margin: 40px auto;
  text-align: center;
}

button {
  margin: 20px;
  padding: 10px 20px;
  font-weight: 600;
  font-size: 110%;
  border: solid 1px grey;
  color: rgb(68, 65, 65);
  border-radius: 3px;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  -ms-border-radius: 3px;
  -o-border-radius: 3px;
  cursor: pointer;
}

Enter fullscreen mode Exit fullscreen mode

We have given our body a default color of purple which is also equal to the color code that is currently displayed on the button (#babfff). We have hidden all the sections except the first one which is for the Hex code and also given our Hex link a text decoration of underline which indicates that the page of this link is currently active. Now let's add some functionality using Javascript.

Adding Javascript

In our Javascript file, lets, first of all, create our variables:

//* variables
// selecting the body element
const changeBackground = document.body;

// selecting the links to change the page
const hexPage = document.getElementById("hex-page");
const rgbPage = document.getElementById("rgb-page");
const hslPage = document.getElementById("hsl-page");

// selecting the main wrappers
const hexWrapper = document.getElementById("hex-wrapper");
const rgbWrapper = document.getElementById("rgb-wrapper");
const hslWrapper = document.getElementById("hsl-wrapper");

// selecting the buttons to change the background
const hexColor = document.getElementById("hex-color");
const rgbColor = document.getElementById("rgb-color");
const hslColor = document.getElementById("hsl-color");

Enter fullscreen mode Exit fullscreen mode

Now that we have done that, let's write some functions for our page links:

//* adding event listener and function to the color page links
// hex page
hexPage.addEventListener("click", function () {
  if (hexPage.style.textDecoration != "underline") {
    hexWrapper.style.display = "block";
    rgbWrapper.style.display = "none";
    hslWrapper.style.display = "none";
    hexPage.style.textDecoration = "underline";
    rgbPage.style.textDecoration = "none";
    hslPage.style.textDecoration = "none";

      // changes the background color

   changeBackground.style.backgroundColor = hexColor.textContent;
  }
});

// rgb page
rgbPage.addEventListener("click", function () {
  if (rgbPage.style.textDecoration != "underline") {
    rgbWrapper.style.display = "block";
    hexWrapper.style.display = "none";
    hslWrapper.style.display = "none";
    rgbPage.style.textDecoration = "underline";
    hexPage.style.textDecoration = "none";
    hslPage.style.textDecoration = "none";

    // changes the background color
    changeBackground.style.backgroundColor = rgbColor.textContent;
  }
});

// hsl page
hslPage.addEventListener("click", function () {
  if (hslPage.style.textDecoration != "underline") {
    hslWrapper.style.display = "block";
    rgbWrapper.style.display = "none";
    hexWrapper.style.display = "none";
    hslPage.style.textDecoration = "underline";
    rgbPage.style.textDecoration = "none";
    hexPage.style.textDecoration = "none";

 // changes the background color
changeBackground.style.backgroundColor = hslColor.textContent;
  }
});

Enter fullscreen mode Exit fullscreen mode

What each function does is that when we click on a page link, it checks if the link that was clicked on is underlined, if it isn't, it then underlines it and the corresponding page/section to that link becomes visible while the remaining pages become invisible with the other links having no line under them.

It also takes the color code that is being displayed in the button that is visible on the page/section and sets the background color of the page to that color.

Next up, is adding functionality to our buttons. We will be using Math.random() and Math.floor() functions for these. But before that let me briefly explain what they do.

The Math.random() and Math.floor() Functions

The Math.random() function, when called, always returns a random decimal number between 0 and 1. If you want to generate random numbers within a given set of numbers, let's say 0 to 10, you would then multiply the decimal number generated by 10.

The Math.floor() when combined with Math.random() just rounds down the number to a whole number.

console.log(Math.random())
// logs out 0.5408145050563944

console.log(Math.random() * 10)
// logs out 5.408145050563944

console.log(Math.floor(Math.random() * 10))
// logs out 5

Enter fullscreen mode Exit fullscreen mode

You can read more on them in the article listed in the Resources Section. Now back to our buttons.

Hex button color generator

Hex color codes are made up of 6 characters prefixed my a ‘#’ (E.g, #434343, #baffff, #d3ded3). The hex characters are always numbers between ‘0’ and ‘9’ or letters between ‘a’ and ‘f’.

We will be generating the 6 characters randomly and string them together to get our random hex color code. Copy the javascript code below:

//* adding event listener and function to the color buttons
// hex button
// array of values for the background color
const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f"];
// a random number value
let randomNumberValue;

hexColor.addEventListener("click", function () {
  // saves the new background color
  let hexColorValue = "#";
  // randomly picks a value in the array and adds it to the background color above
  for (let i = 0; i < 6; i++) {
    randomNumberValue = Math.floor(Math.random() * hex.length);
    hexColorValue += hex[randomNumberValue];
  }
  // changes the text inside the button
  hexColor.textContent = hexColorValue;
  // changes the background color
  changeBackground.style.background = hexColorValue;
});

Enter fullscreen mode Exit fullscreen mode

First of all, we created an array called hex, which contains all the hex characters that are used to create hex codes. We will be getting our random characters from this array.

Next up is a variable called randomNumberValue. This variable temporarily stores any random character we generate.

After that, we created a function that runs any time we click on the button.

In this function, we have another variable called hexColorValue, which is used to store our generated hex code. Initially its value is set to ’#’, but as we generate our 6 random hex characters, they will be added to the hexColorValue to give us a hex color code(i.e ‘#bab434’).

In our for...loop function, we are now generating a random number that falls between 0 and 16 (where 16 is the length of our array) by combining Math.random() and Math.floor() functions. This number will represent the position of each character in the array.

Once the number is generated, the character that is stored in that array position is then added to our current hexColorValue. So if the random number generated is 5, then our hex character will be ‘4’ because its position in the array is 5 and if our random number is 15, then our hex character will be ‘f’ because its array position is 15.

Once we have generated all 6 characters via the for...loop and added them to our hexColorValue simultaneously, the text of our button and the background color of our page is then set to our hexColorValue. And if we were to click on the button again, the whole process gets repeated.

Next up is the RGB button.

RGB button color generator

Rgb color codes are made up of 3 values which are numbers between 0 to 255. The 3 values represent a shade of Red, Green and Blue and that's what rgb stands for.

We are going to generate random numbers for these 3 values and in turn use them to generate our random rgb color code. Copy the javascript code below:

// rgb button
rgbColor.addEventListener("click", function () {
  // randomly picks a number between 0 and 255
  let a = Math.floor(Math.random() * 256);
  // randomly picks a number between 0 and 255
  let b = Math.floor(Math.random() * 256);
  // randomly picks a number between 0 and 255
  let c = Math.floor(Math.random() * 256);
  // saves the new background color
  const rgbColorValue = `rgb(${a}, ${b}, ${c})`;
  // changes the text inside the button
  rgbColor.textContent = rgbColorValue;
  // changes the background color
  changeBackground.style.background = rgbColorValue;
})

Enter fullscreen mode Exit fullscreen mode

So in this function, we created 3 variables a, b and c, and generated random numbers between 0 and 256 for each of them. Each variable represents one of the values of our rgb color code.

Next up we have a variable called rgbColorValue which represents our rgb color code. We are taking our 3 values stored in a, b and c and using them in the template literal that our rgbColorValue is equal to.

Once that is done, the function then replaces the text of our button and the background color of our page to the generated rgbColorValue.

You might have noticed that I multiplied our random number by 256 instead of 255. This is because if we were to use 255, the function would give random numbers below 255 but not the actual 255. So if we want to include 255 as a random number, we have to add 1 to it making it 256.

Hsl button color generator

Hsl color codes are also made up of 3 values but the values and ranges are different. The 3 values they represent are hue, saturation and lightness.

The hue value is between 0 to 360 degrees, while the saturation and lightness are between 0 to 100%.

Our code is going to look similar to that of our rgb button color generator.

// hsl button
hslColor.addEventListener("click", function () {
  // randomly picks a number between 0 and 360
  let a = Math.floor(Math.random() * 361);
  // randomly picks a number between 0 and 100
  let b = Math.floor(Math.random() * 101);
  // randomly picks a number between 0 and 100
  let c = Math.floor(Math.random() * 101);
  // saves the new background color
  const hslColorValue = `hsl(${a}, ${b}%, ${c}%)`;
  // changes the text inside the button
  hslColor.textContent = hslColorValue;
  // changes the background color
  changeBackground.style.background = hslColorValue;
});

Enter fullscreen mode Exit fullscreen mode

Here we are also generating 3 random values within the number ranges for our hue, saturation and lightness and storing them as a, b and c respectively.

We then take the generated values and use them in our variable called hslColorValue which represents our hsl color code.

The background color of our page along with the text of our button is then set to the value of our hslColorValue.

And it's as easy as that.

Conclusion

We created a Color Flipper that changes the background of our page using 3 different color codes on the click of a button.

And with this JavaScript project, we also learnt how to use the functions Math.random() and Math.Floor() to generate random colors in hex, rgb and hsl color codes along with using JavaScript DOM Manipulation.


Till next time guys, Byeeee!

bye(24).gif

Connect with me on

Twitter | LinkedIn | Instagram.


If you like my notes and would like to support me, you can buy me a coffee on ByMeACoffee. I love the taste of coffee.🥰

Resources

💖 💪 🙅 🚩
timonwa
Timonwa Akintokun

Posted on April 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related