DEV Community

Cover image for Project 2: Random Color Flipper in Javascript
Kurapati Mahesh
Kurapati Mahesh

Posted on • Updated on

Project 2: Random Color Flipper in Javascript

To the continuation to project 1, I have improved it to flip to new color every time you click on button.

Here is the implementation:

<html>

<body id="flipper">
    <p id="text" style="font-size:50px">Background Color: <span id="color"></span> </p>
    <button id="btn" style="padding: 14px 28px;" onclick="perform()">Random color!</button>
    <script>
        function perform() {
            const color = '#' + Math.random().toString(16).substring(9);
            document.getElementById('color').innerHTML = color;
            document.getElementById('flipper').style.backgroundColor = color;
        }
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Again, lets understand step by step in the code.

If you see the HTML, there is again button from which the action begins. When user clicks on Random color! button then perform action gets triggered.

In the perform function, we are capturing hexadecimal value of color using '#' + Math.random().toString(16).substring(9); like #9af6bf, #815aab, #c17546 etc.

document.getElementById('color').innerHTML = color; - setting that randomly generated color to span to show on page.
document.getElementById('flipper').style.backgroundColor = color; - Setting as background color of the whole page.

Hope things are clear.

Thanks! Happy Coding 😊.


💎 Love to see your response

  1. Like - You reached here means. I think, I deserve a like.
  2. Comment - We can learn together.
  3. Share - Makes others also find this resource useful.
  4. Subscribe / Follow - to stay up to date with my daily articles.
  5. Encourage me - You can buy me a Coffee

Let's discuss further.

  1. Just DM @urstrulyvishwak
  2. Or mention
    @urstrulyvishwak

For further updates:

Follow @urstrulyvishwak

Latest comments (0)