Change The Background Color of a Button with JavaScript.

Introduction

In this example, we will discuss how we change the Background Color of a Button with JavaScript. Here we will call the function on the onmouseover event of the Button Like this:

1. Create an HTML button element with the desired text and style properties.

<input type="button" value="Button" id="myButton" /> 

In the JavaScript code, use the document.getElementById() method to get the reference to the button element. For example:

const button = document.getElementById("myButton");

Use the button.style.backgroundColor property to set the background color of the button. For example:

button.style.backgroundColor = "red";  

Here is the complete JavaScript code to change the background color of a button on mouseover: 

function changeColor() {
  const button = document.getElementById("myButton");
  button.style.backgroundColor = "red";
}

In this code, the changeColor() function is called on mouseover. The function gets the reference to the button element and sets its background color to red.

The function is called from the button using the following code:

<input type="button" onmouseover="ChangeColor()" value="Button" id="myButton" /> 

You can also use the setTimeout() method to change the background color of the button after a certain delay. For example:

function ChangeColor()  
{  
    const button = document.getElementById("myButton");
    button.style.backgroundColor = "red";
    setTimeout(() => {
      button.style.backgroundColor = "green";
    }, 3000);
    setTimeout(() => {
      button.style.backgroundColor = "yellow";
    }, 6000);
}

In this code, the background color of the button is set to red immediately on mouseover. After 3 seconds, the background color is changed to green. Then, after 6 seconds, it will change to yellow.