How do I change the background color with JavaScript?
Categories:
How to Dynamically Change Background Color with JavaScript
Learn various JavaScript techniques to modify the background color of HTML elements, including the entire page body, using CSS properties and event listeners.
Changing the background color of a webpage or specific HTML elements dynamically is a common requirement in web development. Whether you're building a theme switcher, responding to user interactions, or providing visual feedback, JavaScript offers powerful ways to manipulate CSS properties. This article will guide you through different methods to achieve this, from basic direct manipulation to more advanced techniques using CSS variables.
Changing the Body Background Color
The simplest way to change the background color of your entire webpage is by targeting the <body>
element. JavaScript allows you to access its style
property and directly modify CSS properties like backgroundColor
.
document.body.style.backgroundColor = 'lightblue';
// You can also use hexadecimal or RGB values
// document.body.style.backgroundColor = '#FFD700'; // Gold
// document.body.style.backgroundColor = 'rgb(123, 104, 238)'; // MediumPurple
Directly setting the background color of the <body>
element.
Changing Background Color of Specific Elements
Beyond the <body>
, you'll often need to change the background of individual HTML elements like <div>
s, <span>
s, or buttons. You can achieve this by first selecting the element using methods like getElementById()
, querySelector()
, or querySelectorAll()
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Element Background Change</title>
<style>
#myDiv {
width: 200px;
height: 100px;
border: 1px solid black;
margin: 20px;
background-color: lightgray;
}
</style>
</head>
<body>
<div id="myDiv"></div>
<button onclick="changeDivColor()">Change Div Color</button>
<script src="script.js"></script>
</body>
</html>
HTML structure with a div and a button.
function changeDivColor() {
const myDiv = document.getElementById('myDiv');
if (myDiv) {
myDiv.style.backgroundColor = 'salmon';
}
}
JavaScript function to change the background color of a specific div.
Workflow for dynamically changing an element's background color.
Using Event Listeners for Interactive Color Changes
To make color changes interactive, you'll typically use event listeners. Common events include click
, mouseover
, mouseout
, or change
(for form elements). This allows your webpage to react to user actions and update styles accordingly.
Tab 1
language: html
Tab 2
title: index.html
Tab 3
content:
Tab 4
language: javascript
Tab 5
title: script.js
Tab 6
content: const button = document.getElementById('colorToggleButton'); let isLight = true;
button.addEventListener('click', () => { if (isLight) { document.body.style.backgroundColor = '#333'; // Dark background document.body.style.color = 'white'; } else { document.body.style.backgroundColor = 'white'; // Light background document.body.style.color = 'black'; } isLight = !isLight; });
onclick=""
) directly in HTML for complex applications. Attaching event listeners with addEventListener()
is considered a better practice for separation of concerns and flexibility.Advanced: Using CSS Variables (Custom Properties)
For more maintainable and scalable solutions, especially when dealing with themes or multiple dynamic styles, CSS variables (custom properties) are incredibly useful. JavaScript can read and write these variables, allowing you to control CSS from your scripts without directly touching individual style properties.
:root {
--main-bg-color: lightblue;
--text-color: #333;
}
body {
background-color: var(--main-bg-color);
color: var(--text-color);
transition: background-color 0.3s ease, color 0.3s ease;
}
Defining CSS variables in the :root
pseudo-class.
const root = document.documentElement; // Access the :root element
const toggleButton = document.createElement('button');
toggleButton.textContent = 'Toggle Theme';
document.body.appendChild(toggleButton);
let isLight = true;
toggleButton.addEventListener('click', () => {
if (isLight) {
root.style.setProperty('--main-bg-color', '#222');
root.style.setProperty('--text-color', 'white');
} else {
root.style.setProperty('--main-bg-color', 'lightblue');
root.style.setProperty('--text-color', '#333');
}
isLight = !isLight;
});
JavaScript manipulating CSS variables for theme switching.