Color Flipper using Javascript

Here in this tutorial we are going to learn about color flipping in a web page.

Color Flipper

 

 

A color flipper is a project that show color change effects with some of specific colors and generates random colors and changes the background color when a button is clicked. We’ll look step-by-step with code examples.

1. HTML file:
  • With the html file we inserted four buttons edited with CSS (Cascading style sheet) allows us to change the colors of our web page.
  • There are four buttons that changes the background into green, red, blue and other Random that shows different random colors .
<!DOCTYPE html>
<html lang="en">
<head> 
    <meta charset="UTF-8" /> 
    <meta name="viewport" content="width=device-width, initial-scale=1" /> 
    <link href="color_fliper.css" rel="stylesheet" /> 
</head>
<body>
    <div class="fliper_container">

        <h2>Color Flipper</h2>

        <button id="green" onclick="setColor('green')">Green</button>

        <button id="red" onclick="setColor('red')">Red</button>

        <button id="blue" onclick="setColor('blue')">Blue</button>

        <button onclick="randomColor()">Random</button>

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

    </div>

</body>

</html>
2. CSS file:

 

  • Responsible for styling the web page with the div element that centres the elements of the page and provides its look modification.
  • Contain the rules for the appearance of the div and the button.
body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
    width: 200vh;
}
.fliper_container {

    background: none;
    padding: 30px;
    margin-bottom: 25px;
    border-radius: 5px;
    text-align: center;
    width: 300px;
    border: 5px solid black;
    opacity: 0.7;
}
#green{
    background-color: green;
}

#red{
    background-color: red;
}

#blue{
    background-color: blue;
}
button{
    border-radius: 5px;
    width: 100px;
    height: 40px;
    margin: 5px;
}
h2{
    padding-bottom: 20px;
    font-style: oblique;
}
3. Javascript file:
  • Contains the back end of the web page .
  • This file is use to handle the application logic. In this file, we’ll define the necessary functions and event listeners.
const body = document.getElementsByTagName("body")[0]

function setColor(name) {
    body.style.backgroundColor = name;
}

function randomColor() {
    const red = Math.round(Math.random() * 255) 
    const green = Math.round(Math.random() * 255)
    const blue = Math.round(Math.random() * 255)
    
    const color = `rgb(${red}, ${green}, ${blue})`
    body.style.backgroundColor = color;
}

 

Output:

 

 

We can see the use use of different buttons to change the color of the page . Allows us to add color changing properties to our projects and improves over all appearance of the web pages.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top