Color flipper in JavaScript

Muhammad Saqib Ilyas
6 min readJun 20, 2024

--

Learning to code, in general, and web development in particular is done effectively only by building projects. In this blog, I’ll show you how to code a color flipper tool in JavaScript.

A preview of our application

A color flipper is a tool that displays a random color when you load it. It has a button that allows you to generate another random color. It is a simple enough place to start your learning journey. Let’s dive right in.

Plan

It is important to know what you are trying to achieve and create a plan accordingly. Here’s our plan:

  • Create a web page with an initial background color. White will do.
  • Create a button on the page.
  • Style the button.
  • Center the button on the page horizontally and vertically.
  • Add a click event handler on the button to change the background color.

Starter code

We start with the following HTML file named index.html:

<!DOCTYPE html>
<html>
<head>
<title>Color flipper</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="flip">Flip color</button>
<script src="app.js"></script>
</body>
</html>

The page only has a button with an id attribute of flip. It links to a stylesheet in the same directory as the HTML file. It also imports a script file named app.js in the same directory.

Let’s create the style.css file, first:

*, ::before, ::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}

body {
font-size: 16px;
}

#flip {
background: #333;
color: #ddd;
border: 2px solid white;
width: 150px;
height: 50px;
border-radius: 25px;
}

We start with a CSS reset to get rid of inconsistencies arising from browser-specific default style sheets. We indicate that borders should be included in the block element sizing. We reset margin and padding to zero. On the body element, we set a font size of 16 pixels. This makes it predictable if we use sizing units like em and rem.

Next, we target the color flipping button using an ID selector. We set its background to really dark, and text color really light. We give it a 2 pixel solid white colored border. You wouldn’t be able to see the border yet, because it is the same color as the page background color. We give it a width of 150 pixels, and a height of 50 pixels. We then set the border radius to 25 pixels. Since this is exactly half the height of the button, this creates a rounded capsule like look.

Let’s center the button horizontally and vertically now. We can use several techniques to do it. I’ll use the old-fashioned position attribute instead of more sophisticated approaches like Flexbox. We don’t need that level of sophistication, here. The first thing we must fix is the page’s height. At the moment, the body element is only as high as the button itself.

body {
font-size: 16px;
height: 100vh;
}

We set the page’s height to be 100% of the view height. Next, to horizontally and vertically center the button, we can set the button position as follows:

#flip {
/* Other styles */
position: absolute;
left: 50%;
top: 50%;
}

We declare that the button needs to be taken out of the regular layout flow and be positioned absolutely, with its top left corner 50% of the height away from the top and 50% of the width away from the left edge of one of the elements above it in the DOM. Which element is that? Absolute positioning works relative to any asendant element that has any position attribute value other than static. In our case, we only have the body element above the button. It isn’t really necessary, but we can set this ourselves on the body element:

body {
/* Other styles */
position: relative;
}

At the moment, the button isn’t horizontally and vertically centered,. Instead, its top left corner is horizontally and vertically centered. To fix that, we can apply a transform.

#flip {
/* Other styles */
transform: translate(-50%, -50%);
}

This applies a translate transform on the button. We’re asking the browser to shift the button 50% of its width to the left and 50% of its height upwards. That fixes the horizontal and vertical centering.

Generating random colors

Let’s now focus our attention to generating random colors. We need JavaScript for that. There are various ways to specify a color. One of these is Red-Green-Blue (RGB). It specifies a color as a combination of three primary colors. In RGB, the intensity of each primary color is specified as an integer value between 0 and 255. If we mix each primary color with the intensities of 0 we get a black color. It we mix them with the intensities of 255 each, we get white. There are many colors in between. You might’ve seen color specifications in CSS like background-color: "rgb(23, 165, 87). Here, 23 is the intensity for red, 165 is that for green, and 87 is that for blue.

So, if we were to generate three random integer values between 0 and 255, merge them into a string variable with rgb() around them, then assign it to the background-color property for the page, we are done.

Time to create and edit our app.js file.

function rand255() {
return Math.floor(Math.random()*256)
}

console.log(rand255())

We declare a function named rand255(). From that function we return a value. What is that value? First, we call the Math.random() library function which returns a random fractional value that is greater than or equal to 0, and strictly less than 1. Then, we multiply it with 256. What does that result in? Let’s think about the extreme values. At the lower end, we’re multiplying 0 with 256, which results in 0. At the other end, we’re multiplying a number like 0.9999999 with 256, which results in a number that looks something like 255.99. More than 255, but not quite 256. Next, we take the floor of these extreme values. What do we get? On one end, we get 0. On the other end, we get 255. So, we have our random integer between 0 and 255. We console.log() it on the screen. So, when you refresh the browser, you should see a random integer in the browser console.

Now, we need to generate three random colors, concatenate them into a string. We just need to do something like the following:

console.log('rgb(' + rand255() + ', ' + rand255() + ', ' + rand255() + ')')

We concatenate the string rbg( with a random integer, followed by a comma, followed by another random integer, followed by another comma, followed by another random integer, followed by a closing bracket. Now, if you refresh the page, you should see something like rgb(16, 88, 237) on the browser console.

Let’s write the code to set this string to the background-color property of the body element.

function setBG() {
document.body.style.backgroundColor = 'rgb(' + rand255() + ', ' + rand255() + ', ' + rand255() + ')'
}

setBG()

We declare a function named setBG() short for “set background.” In the function, we put our trusty JavaScript string concatenation code on the right hand side of an assignment statement. We assign this to the backgroundColor attribute of the style attribute of the body element. Note that the background-color CSS attribute is referred to as backgroundColor in JavaScript. We insert a call to this function. Now, if you refresh the page, you should see the background changing colors. Now, do you see the button’s white border?

Let’s now hook up this setBG() function to the button click event handler. That is as simple as changing the button element in HTML to:

<button id="flip" onClick="setBG()">Flip color</button>

Now, clicking the button changes the background color. What’s more, the page loads with a random, most-likely non-white background color. Let’s make one final change:

#flip {
/* Other styles */
cursor: pointer;
}

We change the cursor for the button to pointer so that the cursor changes shape when the user hovers over it. This gives the user a visual cue that this button is an active element.

That’s all folks!

That concludes our project. Keep learning. Can you try to set the background color using hexademical color values like #54A3D3? Can you add a div element in the body element and change its background color rather than that of the entire body element? Can you attach the click event handler to the button in JavaScript rather than HTML?

Here’s the HTML:

<!DOCTYPE html>
<html>
<head>
<title>Color flipper</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="flip" onClick="setBG()">Flip color</button>
<script src="app.js"></script>
</body>
</html>

Here’s the CSS:

*, ::before, ::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}

body {
font-size: 16px;
height: 100vh;
position: relative;
}

#flip {
background: #333;
border: 2px solid white;
border-radius: 25px;
width: 150px;
height: 50px;
color: #Ddd;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}

Here’s the JavaScript:

function rand255() {
return Math.floor(Math.random()*256)
}

function setBG() {
document.body.style.backgroundColor = 'rgb(' + rand255() + ', ' + rand255() + ', ' + rand255() + ')'
}

setBG()

You may also clone the project from this Github repository.

--

--

Muhammad Saqib Ilyas

A computer science teacher by profession. I love teaching and learning programming. I like to write about frontend development, and coding interview preparation