Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 24, 2022 03:57 pm GMT

Project 2: Random Color Flipper in Javascript

To the continuation to project 1, I have improved 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>

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


Original Link: https://dev.to/urstrulyvishwak/project-2-random-color-flipper-in-javascript-3i6

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To