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

2 responses to “Change Background Color on Mouse Hover in JavaScript”

  1. Jeffrey Amen says:

    Hi, thank you for this. I’m just a beginner. I tried using this and I might have a syntax error but I can’t see it. Here’s my code:

    document.getElementById(“top-container”).style.background-color= “gold”;
    document.getElementById(“top-container”).addEventListener(“mouseout”, function() {
    document.getElementById(“top-container”).style.background-color= “red”;

    the error message says “invalid left hand side in assignment”
    thanks for any help you can give me.

    • Jacky says:

      @Jeffrey you wrote “background-color” but it’s supposed to be “backgroundColor”. That might be what’s causing the issue.

Leave a Reply

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