DEV Community

Cover image for Random Background On clicking button in JS || 10 JS Project Challenge #1
VECTOR3Studio
VECTOR3Studio

Posted on • Edited on

Random Background On clicking button in JS || 10 JS Project Challenge #1

Hello πŸ‘‹

In this post I will show you how to make Random Background, when you click a button in JavaScript.

This is Part 1 of the 10 JS Project Challenge.

So let's get into it.

First, here is the video tutorial:

So let's start coding.

First, we need to create 3 files in our folder.

  • index.html

  • style.css

  • home.js

Once we have those files created, we can start coding.

Here is the code for index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <button">Click Me</button>
    <script src="home.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

We are just creating a basic HTML structure and a Button. We need to link our CSS and JS files too.

Now, let's do style.css.
Here is the code:

body{
    background-color: red;
    display: flex;
    justify-content: center;
    align-items: center;
}
button{
    padding: 14px 24px;
    font-size: 24px;
    border: none !important;
    outline: none !important;
    border-radius: 20px;
    background: white;

}
Enter fullscreen mode Exit fullscreen mode

In CSS, we are just styling our body and a button.

And finally, let's make our JavaScript.
Add this code to your home.js:

function changeBg(){
    document.body.style.backgroundColor = 'rgb(' + Math.round(Math.random() * 255) + ',' + Math.round(Math.random() * 255) + ',' + Math.round(Math.random() * 255) + ')';
}
Enter fullscreen mode Exit fullscreen mode

What this code does is make a function, and in this function is setting and body Background Color to RGB(Random, Random, Random). And that is how we can achieve a Random Color Generation.

We ain't done yet, we need to add this function to our button, so when we click, a background color will be randomly chosen.
You can achieve this simply by adding a onclick fucntion to the button in our index.html.

<button onclick="changeBg()">Click Me</button>

Image description

And now we are done! You should see a color change every time you click a button. Great Work.

Thanks for reading my post, and I hope I will see you next Time.

Top comments (0)