Change Background Color on Mouse Hover in JavaScript

In this JavaScript HTML DOM tutorial, I am going to show you how we can change the background color of an element.

Before we get started, let’s create an HTML element with an ID:

<div id="myID"></div>

Now add some CSS style to give it a height and width as well as the background color red:

#myID {
  height: 400px;
  width: 500px;
  background-color: red;
}

Now if we run the code, we will able to see a rectangle with the red background color. In this time, there will be no change in background color occur if we mouse over the element. To change the background color, we need to write some JavaScript code that is given below:

    
document.getElementById("myID").addEventListener("mouseover", function() {
    document.getElementById("myID").style.backgroundColor = "green";
});
    
document.getElementById("myID").addEventListener("mouseout", function() {
    document.getElementById("myID").style.backgroundColor = "red";
});

In the above JavaScript code, first, we use the mouseover event to change the background color from red to green.

We also want to bring back the color to red after we move our mouse out of the element. So we have also used the mouseout event. This event will occur when we will remove our mouse cursor from the element.

Now we are ready to run our code. let’s see how it works if we test it on our browser.

If you run the complete code on your browser, then you will be able to see the red rectangle. But after you keep your mouse cursor over the element, the color will change into the green. When you remove the mouse cursor from the element, the background color will again come back to red.

So we are able to successfully change the background color on mouse hover with JavaScript.

Also, read: Get each color component from RGB string in Javascript

Leave a Reply

Your email address will not be published. Required fields are marked *