This content originally appeared on DEV Community and was authored by VECTOR3Studio
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 50 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>
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;
}
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) + ')';
}
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>
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.
This content originally appeared on DEV Community and was authored by VECTOR3Studio
VECTOR3Studio | Sciencx (2021-12-19T10:01:49+00:00) Random Background On clicking button in JS || 50 JS Project Challenge #1. Retrieved from https://www.scien.cx/2021/12/19/random-background-on-clicking-button-in-js-50-js-project-challenge-1/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.