How to change background color when button is clicked in JavaScript?

Asked 19-Jul-2021
Updated 16-Jun-2023
Viewed 581 times

2 Answers


0

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
});

 


2

<!DOCTYPE html>

<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta charset='utf-8' />
    <title>JS Demo</title>
    <style type='text/css'>
        * {
            margin:10px;
            padding:0px;
        }
        select {
            width:100px;
        }
    </style>
    <script type='text/javascript'>
        function changeColor() {
        var name = window.document.getElementById('color');
        //alert('Your selected color is : ' + name.value);
        name.style.backgroundColor = name.value;
        window.document.body.style.backgroundColor = name.value;
        window.document.getElementById('sub').style.backgroundColor = name.value;
    }
    </script>
</head>
<body>
    <span>Select Color name : </span>
    <select name='color' id='color' >
        <option value='red'>Red</option>
        <option value='yellow'>Yellow</option>
        <option value='white'>White</option>
        <option value='pink'>Pink</option>
        <option value='green'>Green</option>
    </select>
    <button type='button' onclick='changeColor()' value=' Submit ' id='sub'> Submit </button>
</body>
</html>