To change the background color when a button is clicked using JavaScript, you can follow these steps:
HTML: Start by creating a button element and giving it an id or class for easy identification. Also, make sure to set an initial background color for the element you want to change. For example:
<button id="changeColorButton">Change Color</button>
<div id="targetElement" style="background-color: #f0f0f0; width: 200px; height: 200px;"></div>
JavaScript: Next, you need to add an event listener to the button element and define a function that will be executed when the button is clicked. Inside that function, you can change the background color of the target element. Here's an example using plain JavaScript:
// Get the button and target element by their respective IDs
var button = document.getElementById('changeColorButton');
var targetElement = document.getElementById('targetElement');
// Add a click event listener to the button
button.addEventListener('click', function() {
// Change the background color of the target element
targetElement.style.backgroundColor = 'red'; // Change it to the desired color
});