How to change image on hover in JavaScript

In this poist, we will learn how to change the <img> tag src (source) on hover using JavaScript.

We can change the image source in Javascript:

  1. Use onmouseover() event to change the image when the mouse hovers over the element.
  2. Use onmouseout() event to change back the image when the mouse leaves the element.

Let’s see with an example.

Let’s create an HTML <img> tag with onmouseover() and onmouseout() events.

<img src="image1.jpg" onmouseover="newImg(this)" onmouseout="oldImg(this)">

Now, lets create the newImg() and oldImg() functions.

<script>
  function newImg(e){
    e.src = "image2.jpg"
  }
  function oldImg(e){
    e.src = "image1.jpg"
  }
</script>

In the above code, when we hover our mouse over the image, the onmouseover() event triggers the newImg() function which changes the source (src) of the <img> tag to “image2.jpg “.

And as soon as the mouse leaves the image, the onmouseout() event triggers the oldImg() function that changes the image back to the previous one i.e “image1.jpg“.


Related Topics:

How to change image source using CSS

Change image src using onClick event in JavaScript

Scroll to Top