Changing Background Color with JavaScript: A Step-by-Step Guide

Posted by

In this tutorial, we’ll learn how to dynamically change the background color of a webpage using JavaScript. This can be a useful feature for enhancing user experience and adding interactivity to your website.

HTML Structure:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Background Color - Wizbrand</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <h1>Change Background Color</h1>
        <button id="colorBtn">Change Color</button>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS Styling:

body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
    margin: 0;
    padding: 0;
}

.container {
    text-align: center;
    margin-top: 100px;
}

h1 {
    color: #333;
}

button {
    padding: 10px 20px;
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 16px;
    outline: none;
}

button:hover {
    background-color: #0056b3;
}

JavaScript Code:

// Get the button element
const colorBtn = document.getElementById('colorBtn');

// Add click event listener to the button
colorBtn.addEventListener('click', () => {
    // Generate a random color
    const randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);
    
    // Change the background color of the body
    document.body.style.backgroundColor = randomColor;
});

Output:-

JavaScript code to change the background color when the button is clicked.

Hopefully, it will help you ..!!!

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x