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.


Kumuda LokeshPosted Jun 26, 2013, 4:15 PM
Hi I have a question want to know if anyone can help me.. I juz started to program in HTML and trying to make a program where in you have three color buttons red, blue and green and first time when u press the color it should display red when i press red button and second time when i press blue button it should display text changed from red to blue and when i press red it should display text changed from blue to red so on and so forth.. how do i go abt wri\ting html/javascript code for this>