Are you looking to add some interactive elements to your web page? A simple yet effective way to enhance user engagement is by allowing them to change the background color of the page with just a click of a button. In this tutorial, we’ll walk you through the process of creating a web page that accomplishes this using plain JavaScript. This approach is perfect for beginners and those who wish to brush up on their JavaScript skills.
Getting Started
First, ensure your HTML structure is set up with a class-named main
where our button will reside. This minimal setup is all you need to get started:
<div class="main"></div>
The JavaScript Magic
Now, let’s dive into the JavaScript part. We’re going to create a button dynamically and append it to our .main
div. This button, when clicked, will change the background color of the entire page. Here’s the simple script to achieve this:
const main = document.querySelector('.main');
const btn = document.createElement('button');
btn.textContent = 'Click Me';
main.append(btn);
btn.addEventListener('click', () => {
const bgBody = document.body.style;
if (bgBody.backgroundColor == 'red') {
bgBody.backgroundColor = '';
} else {
bgBody.backgroundColor = 'red';
}
});
How It Works
- We select the
.main
div and create a new button element. - The button is labeled “Click Me” and appended to the
.main
div. - An event listener is added to the button. When clicked, it checks the current background color of the body.
- If the background is already red, it will reset to the default. If not, it changes the background to red.
Conclusion
With just a few lines of JavaScript, you’ve created a dynamic and interactive web page feature. Experiment with different colors and elements to see what else you can achieve with this simple yet powerful technique. Happy coding!
Change Background Color
Objective: Create a web page with a button that changes the background color of the page when clicked.
const main = document.querySelector(‘.main’);
const btn = document.createElement(‘button’);
btn.textContent = ‘Click Me’;
main.append(btn);
btn.addEventListener(‘click’,()=>{
const bgBody = document.body.style;
if( bgBody.backgroundColor == ‘red’){
bgBody.backgroundColor = ”;
}else{
bgBody.backgroundColor = ‘red’;
}
})