How to Change Background Image of DIV on Mouseover in Javascript

In this tutorial, you will learn how to change background image of div on mouseover in javascript. To add a background image to any element, you can make use of the backgroundImage property. The image which you are planning to use as a background image can come from a local directory or a remote server.

You may have seen some websites where they change the background image of an element on mouse hover. Such a thing can be done easily using javascript. Generally, the main element behind the scene is the div element with an image as background.

Each element has a style property that helps in manipulating CSS properties.  One of those CSS properties is the backgroundImage property which can be used to get the background image and set an image as background.

In the following example, we have a div element with 1.jpg as its background image.  On mouse hover, we will change the background image to 2.jpg. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have an empty div element with 1.jpg as its background image. This background image will be changed dynamically using javascript.
  • We have an images folder with 2 images 1.jpg and 2.jpg. You can use any 2 images of your choice.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div></div>
    
    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

div {
    height: 400px;
    width: 400px;
    border: 1px solid black;
    display: inline-block;
    background-image: url('images/1.jpg');
}

Javascript

  • We have selected the div element using the document.querySelector() method and stored it in the myDiv variable.
  • We have attached mouseover and mouseleave event listeners to the div element.
  • In the mouseover event handler function, we are changing the background image of the div element from 1.jpg to 2.jpg using the backgroundImage property.
  • In the mouseleave event handler function, we are setting the backgroundImage property to null which in turn will switch the background image back to the default 1.jpg.
let myDiv = document.querySelector('div');

myDiv.addEventListener('mouseover', () => {
    myDiv.style.backgroundImage = `url('images/2.jpg')`;
});

myDiv.addEventListener('mouseleave', () => {
    myDiv.style.backgroundImage = null;
});