How to change image on hover in JavaScript

featured Image

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

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more

Leave a Reply

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