How to Change an Element's Background Color on Click in JavaScript
Changing an element's background color when a user clicks it is a fundamental DOM manipulation task in JavaScript. This provides immediate visual feedback and is a key building block for creating interactive and dynamic web pages.
This guide will teach you the standard method for changing the background color using a click event listener. You will learn how to change the color of the clicked element itself, the entire page body, or another element entirely. Finally, you will see how to "toggle" the color or cycle through a list of colors on each click.
Core Task: Handling a Click Event
The first step is to select a "trigger" element from the DOM (like a button) and attach a click event listener to it. This listener will execute a function whenever the user clicks that element.
First, we need a button and some other elements in our HTML with unique IDs so we can select them.
<!DOCTYPE html>
<html>
<body>
<div id="box">Some text here</div>
<button id="color-button">Change Color</button>
<script src="index.js"></script>
</body>
</html>
// 1. Select the button from the DOM
const btn = document.getElementById('color-button');
// 2. Add a 'click' event listener
btn.addEventListener('click', function(event) {
// 3. This code will run every time the button is clicked
console.log('Button was clicked!');
});
Solution 1: Change the Clicked Element's Color
Inside the event handler function, the event object contains information about the click. The event.target property is a reference to the element that was clicked. We can use this to change the element's own color.
const btn = document.getElementById('color-button');
btn.addEventListener('click', function(event) {
// `event.target` refers to the button that was clicked
event.target.style.backgroundColor = 'salmon';
});
When the button is clicked, its own background color will change to salmon.
Solution 2: Change the Page's Background Color
To change the background color of the entire page, you need to target the document.body element.
const btn = document.getElementById('color-button');
btn.addEventListener('click', function onClick() {
// Set the background color of the <body> element
document.body.style.backgroundColor = 'lightblue';
});
Now, clicking the button will change the background color of the whole page.
Solution 3: Change Another Element's Color
You can also have a click on one element affect a completely different element. To do this, you select the target element inside your event handler.
const btn = document.getElementById('color-button');
btn.addEventListener('click', function onClick() {
// Select the target element inside the handler
const boxElement = document.getElementById('box');
// Change the style of the target element
boxElement.style.backgroundColor = 'coral';
});
In this case, clicking the button will change the background color of the div with the ID box.
Advanced Technique: Toggling or Cycling Through Colors
For a more dynamic effect, you can make the color change on each click.
How to Toggle Between Two Colors
This example toggles a button's color between two states.
const btn = document.getElementById('color-button');
btn.addEventListener('click', function onClick() {
if (btn.style.backgroundColor === 'salmon') {
btn.style.backgroundColor = 'lightblue';
} else {
btn.style.backgroundColor = 'salmon';
}
});
How to Cycle Through an Array of Colors
This is a more scalable approach for multiple colors.
const btn = document.getElementById('color-button');
const colors = ['#007bff', '#28a745', '#dc3545', '#ffc107'];
let currentIndex = 0;
btn.addEventListener('click', function onClick() {
btn.style.backgroundColor = colors[currentIndex];
// Move to the next color, or loop back to the start
currentIndex = currentIndex >= colors.length - 1 ? 0 : currentIndex + 1;
});
A Note on CSS vs. Inline Styles
The .style property in JavaScript sets inline styles. While this works perfectly, for more complex applications, the best practice is to toggle CSS classes instead, as it separates your styling (CSS) from your logic (JavaScript).
.highlighted {
background-color: salmon;
color: white;
}
btn.addEventListener('click', function onClick() {
document.body.classList.toggle('highlighted');
});
Conclusion
Changing an element's background color on click is a fundamental DOM manipulation technique.
To do it successfully:
- Select a trigger element from the DOM (e.g., a button).
- Add a click event listener with
addEventListener('click', function() { ... }). - Inside the handler function, target the desired element (
event.target,document.body, or another selected element) and modify its.style.backgroundColorproperty. - For dynamic effects, use conditional logic or an array of colors to change the style on each subsequent click.