Get the 2024 Yearly Goals and Progress Tracker Notion Template for FREE!

How to Build a Random Color Flipper with Vanilla Javascript

SERIES: JavaScript Projects for Beginners

Updated on: Nov 2, 2023

12 mins read


Color Flipper is a simple random color generator that changes the background of a web element to that random color, at the click of a button.

How to Build a Random Color Flipper with Vanilla Javascript

Hi guys, and welcome to the second article in my JavaScript Projects for Beginners Series. In this series, I will be building 10+ Javascript projects to test and develop our Javascript coding skills.

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

Project Code and Live Demo:

You can access all the project code on my GitHub repository. Additionally, explore the live demo to interact with the finished projects.

Prerequisites

Before we dive into creating accordions, I assume you understand HTML, CSS, and JavaScript. Familiarity with JavaScript DOM manipulation will be helpful.

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 simple application where you have a button that, on click, runs a function that generates a random color and then sets the color of an element you preselected to that random color.

A random color flipper

A random color flipper

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

Building the Color Flipper

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

Adding Html

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

html
<!-- 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>

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

All three sections are visible; only one will be visible at a time when we add our CSS styles. With Javascript, we will use our links to toggle on and off the visibility of each section corresponding to that 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:

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;
}

We have given our body a default color of purple, which also equals the color code 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, indicating that this link's page is currently active. Now, let's add some functionality using Javascript.

Adding Javascript

In our Javascript file, let us, first of all, create our variables:

js
//* 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");

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

js
//\* 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;
}
});

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

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

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

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

When called, the Math.random() function 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.

When the Math. random() is combined with Math.floor(), it rounds down the number to a whole number.

js
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

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

Hex button color generator

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

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

js
//\* 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;
});

First, we created an array called hex, which contains all the hex characters used to generate 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 whenever we click the button.

In this function, we have another variable called hexColorValue, which stores our generated hex code. Initially, its value is set to '#', but as we generate our six 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 stored in that array position is added to our current hexColorValue. So if the random number generated is 5, our hex character will be 4 because its position in the array is 5. If our random number is 15, our hex character will be f because its array position is 15.

Once we have generated all six 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 would be 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 three values represent a shade of Red, Green, and Blue, and that's what rgb stands for.

We will generate random numbers for these three values for our random rgb color code. Copy the javascript code below:

js
// 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;
});

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

Next, we have a variable called rgbColorValue, representing our rgb color code. We are taking our three values stored in a, b, and cand using them in the template literal to which ourrgbColorValue is equal.

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

You might have noticed that I multiplied our random number by 256 instead of 255. It 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 must add 1, making it 256.

Hsl button color generator

Hsl color codes are also made up of 3 values, but the values and ranges differ. The three 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 will look similar to that of our rgb button color generator.

js
// 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;
});

Here, we generate three random values within the number ranges for our hue, saturation, and lightness and store them as a, b, and c, respectively.

We then take the generated values and use them in our variable, 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.

A random color flipper

A random color flipper

Conclusion

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

With this JavaScript project, we also learned 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, would you be trying this out? Let me know in the on X (Twitter). Tell me, what JavaScript project would you like me to build next?

Till next time, guys, Byeeee!

man smiling and waving goodbye

Image from

giphy.com

Resources

Connect With Me

Follow me on X(Twitter), and LinkedIn to stay updated with my latest content.

If you like my notes and want to support me, you can sponsor me on GitHub Sponsor, or you can buy me a virtual ice cream on ByMeACoffee or Selar. I would really appreciate it. 🙏

For other ways to support me, visit my Sponsorship page or Affiliate Links page.

Frequently Asked Questions

1. What is a color flipper in web development?

A color flipper, in web development, refers to a simple application or script that generates random colors or allows users to cycle through predefined colors with the click of a button. It's often used for design or development purposes to quickly experiment with different color schemes, test contrasts, or add visual interest to web projects.

2. How can I create a basic color flipper for my website?

To create a basic color flipper for your website, you can use HTML, CSS, and JavaScript. Start by defining a set of colors you want to flip between, then use JavaScript to generate a random color or cycle through the predefined colors when a user interacts with the page. CSS is used to apply the chosen color to the background or other elements. There are also libraries and tools available to simplify this process.

3. Are there any libraries or frameworks for building advanced color flippers?

Yes, there are several libraries and frameworks that can help you build advanced color flippers. Some popular options include TinyColor, Chroma.js, and D3.js. These libraries offer features like color manipulation, gradient generation, and more. You can integrate them into your projects to create more sophisticated color-flipping applications.

4. What are some creative use cases for a color flipper in web design?

Color flippers can be creatively used in web design for various purposes. For example, you can use them to create eye-catching backgrounds, design interactive elements that change color on user interaction, or even build games and puzzles based on color patterns. They add an element of surprise and engagement to your website.

5. Are there any accessibility considerations when using color flippers?

Yes, accessibility is essential when using color flippers. Ensure that the colors you use have sufficient contrast to meet accessibility standards, making content readable for all users, including those with visual impairments. You should also provide controls or options for users to pause, stop, or customize the color flipping to accommodate various preferences and needs.

Subscribe to my newsletter 💌

Stay in the loop on the latest articles, tutorials, projects, and exclusive content focused on web development! 💻📚✨