To change the background color of an element on button click, first attach a click event listener to the button using the addEventListener()
method and then use the style.backgroundColor
property to change the background color.
For example, Let’s say we have a <p>
and a button in our HTML document. The <p>
initially has a green background color.
We want to change the background color of the <p> from green to yellow as soon as we click the button:
<button id="myBtn">Change Background</button> <p id="target">This is some random text.</p>
Add the CSS:
p{ padding: 10px; background-color: springgreen; }
Add the JavaScript:
// Get references to the elements const btn = document.getElementById('myBtn'); const target = document.getElementById('target'); // Attach click event listener to the button btn.addEventListener('click', function(){ // Change the bg color to 'yellow' target.style.backgroundColor = 'yellow'; });
Output:
Change the Background Color of the Entire Body on Button Click
If you want to change the background color of the entire body of the page instead of a particular element on button click, you can first access the <body> element using the document.body
and then use the style.backgroundColor
property to set the background color.
The following example sets the background color of the document’s <body>
to yellow on button click:
// Get reference to the button const btn = document.getElementById('myBtn'); // Attach a click event listener to the button btn.addEventListener('click', function(){ // Change the bg color to 'yellow' document.body.style.backgroundColor = 'yellow'; });
Output:
Toggle the Background Color on Button Click
If you want to toggle the background color between two colors, you have to first get the value of the current background color using the style.backgroundColor
property and then set it to another background color.
The following example toggles the background color of the entire page between yellow and springgreen on button click:
// Get reference to the button const btn = document.getElementById('myBtn'); // Attach a click event listener to the button btn.addEventListener('click', function(){ // Check if the current bg color is yellow if(document.body.style.backgroundColor == 'yellow'){ // Set the background color to 'springgreen' document.body.style.backgroundColor = 'springgreen'; } else{ // Set the bg color to 'yellow' document.body.style.backgroundColor = 'yellow'; } });
Output:
If you want to toggle the background color between more colors, you can add more if...else
statements.
Thanks for reading.