DEV Community

Cover image for How To Create color Flipper using vanilla Javasscript
Dennis Ng'ang'a Mbugua
Dennis Ng'ang'a Mbugua

Posted on

How To Create color Flipper using vanilla Javasscript

Introduction

Javascript is used in creating web pages. Javascript allows adding dynamic behaviour and interactivity user experience.
A colour flipper is a simple interactive tool that changes the background color of the HTML element by clicking a button. With the click of a button, a function is run that generates a random colour on the set Background.
Practice makes perfect and to understand Javascript concepts, one needs substantial time and consistency in practice.
The colour flipper is a basic project and understanding how it works will give you a hands-on- approach to a practical understanding of javascript concepts.
In this article, you are going to dive into a colour flipper project using HTML, CSS, and JAVASCRIPT.
When you are finished, you will have covered the following;

  • DOM manipulation
  • Javascript arrays
  • Math. random()
  • Math. floor()
  • Javascript functions

Pre-requisites

Before you dive into this blog, you need to have the following:

  • Visual Studio Code installed to write your HTML, CSS, AND JavaScript code. Follow this link to Download Visual Studio Code
  • Working with files. You can successfully create folders, files and navigate through them in VSCode. Get started with this on Mozilla Developer Docs
  • A web browser to test and view the colour flipper. Google Chrome, Mozilla Firefox, Microsoft Edge, or Safari are suitable choices.

Step 1-Creating Our Files

To get started with creating our colour flipper, we first need to open our code editor and create 3 files index.html, index.css, and index.js.

Step 2- Adding the HTML Code

Inside our HTML file, we will add the following code:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>color flipper</title>
    <!-- css -->
    <link rel="stylesheet" href="index.css">
</head>
<body>

    <!-- HEADER  -->
    <header>
        <h1>Color Flipper</h1>
    </header>
    <!-- MAIN  -->
    <main>

        <div class="container">
            <h2>Background Color <span id="value">#0a0a23</span></h2>

            <div class="button-container">  <!--div containing button-->
            <button id="btn">click me</button>
        </div>

        </div>
    </main>

    <!-- Javascript -->
    <script src="index.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Let me explain the above code in our HTML file.
The file contains:

  • Firstly, we have linked our HTML to our CSS for styling.


    <link rel="stylesheet" href="index.css">

  • Secondly, we added script tag to link to the javascript file

    <script src="index.js"></script>

  • A header with the Color Flipper text. This explains what our project is about.

  • We also created a div container in our main tag that contains an h2 text Background Color and span text of the current body background colour. Also, we have a div that contains a button that changes the body background color style when clicked.

Note: The span and the button tags have unique IDs, enabling us to target them with javascript.

## Step 3-Adding CSS code
So, let us add our CSS code to the index.css file :

/* css reset */
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

/* general styling */

body{
   min-height: 100vh;/* set body min-height to at least 100% viewports height*/
    background-color: #0a0a23;
    color: #fff;
    text-align: centre;

} 

/* --------------  CONTAINER STYLES*
-------------------*/
.container{
    text-align: center;
}
main{
    min-height: 100vh;
    display: grid;
    place-items: center;
}

.container h2{
    margin-bottom: 2rem;
    background-color: coral;
    padding: 1rem;
    border-radius: 10px;
}

/* button styling */
#btn{
    font-family: sans-serif;
    text-transform: uppercase;
    background: transparent;
    color: #fff;
    letter-spacing: 1.2;
    display: inline-block;
    font-weight: 700;
    transition:0.3s;
    border: 2px solid coral;
    cursor: pointer;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
    border-radius: 8px;
    font-size: 1rem;
    padding: 0.75rem 1.25rem;
}
#btn:hover,:focus{
    opacity: 0.7;
    background-color: #999;
    cursor: pointer;
} 
Enter fullscreen mode Exit fullscreen mode

Using the Css code above, we have done the following:

  • Reset the default styles using the * universal selector.
  • Set the body styles to a min- height to 100% of the viewport height.
  • Center the main content using CSS Grid.
  • Added styles to the button with ID of "btn" and hover effects.

    • After adding the css code, save and refresh the browser for result. Now the page looks like this with CSS styles See the Pen Untitled by Dennis Mbugua (@mbuguadev) on CodePen.

## Step 4-Adding Functionality with Javascript

Now that our HTML and CSS codes are set, it is time write our javascript code.We are going to add functionality to the color flipper.

In our javascript code, we will first need to do the following:

  1. Create an array that contains the HEX color characters.

let hexCharacters = [0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F"];

HEX colors values contains combination of 6 characters from the set of 0-9 and A-F. We have stored the characters in hexCharacters variable.

Select our span and button elements using their respective ID.

   const spanValue = document.getElementById('value');
const clickButton = document.getElementById('btn');
Enter fullscreen mode Exit fullscreen mode

We have used the Javascript in built method document.getElementById that helps to retrieve a reference to a HTML element using the element's ID.
The spanValue and clickButton variables stores references to HTML elements with the IDs 'value' and 'btn', respectively.

Now that we are done creating variables, let us add the functions to our javascript code:

   // create an event listener to button
clickButton.addEventListener('click', function(){
    getRandomCharacter(); // call the getRandomCharacter function on click

});

// function to generate HEX value characters
function getRandomCharacter(){

    let hexColorCharacters = "#";  //intial value of of our color value

    for(let i=0; i<6;i++){
        hexColorCharacters +=hexCharacters[generateRandomNumber()];  
    }

    spanValue.textContent = hexColorCharacters; // set the span text content to current background color value

    /*set body background color to  hexColorCharacters;
    it contains 6 random characters generated from hexCharacters array */
    document.body.style.backgroundColor = hexColorCharacters;
}

/*function that generates random numbers
//generates numbers between 0 and 16 */

function generateRandomNumber(){
    return Math.floor(Math.random() * hexCharacters.length);
}
Enter fullscreen mode Exit fullscreen mode

This is what we have done in the above javascript code:

*Step I:
we have created an event listener to our button with the ID "btn".
We want an event( in this case a click event) to happen when the button is clicked.
When the button is clicked, it triggers the function specified.

Step II:
The event listener triggers anonymous function(function without a name), when button is clicked.
Now, inside this anonymous function, we call the **getRandomCharacter()
*
function

Step III: What is happening inside the **getRandomCharacter()* function:

In this function, we have a variable hexColorCharacters which starts with "#" (a valid starting character for HEX colors).
when the loop runs, it appends a random HEX characters from the hexCharacters array, forming a complete 6-character HEX color code.

In the for loop, we generate a random HEX color value by selecting random characters from a list of valid HEX characters, which includes numbers 0-9 and letters A-F(as we said above). The loop runs six times, with each iteration appending a new random character to the hexColorCharacters variable, initially set to "#" as the valid HEX color prefix. After completing the loop, the hexColorCharacters holds a complete 6-character random HEX color value. For example("#4B32BD");

The function also:

  • Sets this hexColorCharacters as the content of the span using textContent.
  • Sets the background color of the webpage body (document.body.style.backgroundColor) to the generated HEX color. Step IV The function **generateRandomNumber()* utilizes the Math.random() and Math.floor() mathods to generate random numbers between 0 and 15 (hexCharacters.length - 1). We noe use the function to index into the hexCharacters array, and pick a random HEX character.

Here is the complete javascript code in our index.js file:

//  create a variable to store HEX character combination
let  hexCharacters = [0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F"];


// Select span and button element using their ID values

const spanValue = document.getElementById('value');
const clickButton = document.getElementById('btn');


// create an event listener to button
clickButton.addEventListener('click', function(){
    getRandomCharacter(); // call the getRandomCharacter function on click

});

// function to generate HEX value characters
function getRandomCharacter(){

    let hexColorCharacters = "#";  //intial value of of our color value

    for(let i=0; i<6;i++){
        hexColorCharacters +=hexCharacters[generateRandomNumber()];  
    }

    spanValue.textContent = hexColorCharacters; // set the span text content to current background color value

    /*set body background color to  hexColorCharacters;
    it contains 6 random characters generated from hexCharacters array */
    document.body.style.backgroundColor = hexColorCharacters;
}

/*function that generates random numbers
//generates numbers between 0 and 16 */

function generateRandomNumber(){
    return Math.floor(Math.random() * hexCharacters.length);
}
Enter fullscreen mode Exit fullscreen mode

Give yourself a part on the back for the great work. Now that we have completed our code, click the button to start playing with the color flipper.

See the result in codepen

See the Pen
Untitled
by Dennis Mbugua (@mbuguadev)
on CodePen.

Conclusion

You have successfully created a color flipper that changes the background of our page on the click of a button.
With this Javascript project, you have learnt how to generate random numbers using Math.random() and Math.floor() methods. Along the way, you have learnt Javascript DOM manipulation and how to write reusable code with Javascript functions. It is my hope that you will use these concepts in your next project.

Let me know how you felt about this on Twitter

Written by Dennis Mbugua

Top comments (0)