JavaScript

How to Change Image on Hover in JavaScript

On web pages, changing images on the hover effect is a common task. The specific task of toggling images on the hover is mostly used on web pages. To do this, use the HTML attributes “onmouseover” and “onmouseout” in JavaScript to trigger functions.

This post will demonstrate the procedure to change the image on hover in JavaScript.

How to Change an Image on Hover in JavaScript?

For changing the image on the hover, use the “onmouseover” event. When the mouse/cursor is moved through an HTML element or one of its children, the onmouseover event is triggered.

Example 1: Change Image on Hover in JavaScript
In an HTML file, use the <img> tag to show the image on a web page. Attach the “onmouseover” event that will call the JavaScript function when the mouse hovers over the image:

<img id='menuImg' src="1.jpg" onmouseover="hover(this);"/>

In a JavaScript file, define a function “hover” with the parameter “img”. In the defined function, set the image that will be shown on the hover:

function hover(img)
{
 img.src = "2.jpg"
}

As you can see, in the output, when we hover over the current image, it suddenly changes:

Example 2: Toggle the Image on Hover
In the above example, the image changes when the mouse is hovering over the image, and the same image remains. Now, in this example, the first image will reappear when the mouse moves out of the image. This effect is called the toggling effect. For this purpose, we will use the “onmouseover” and “onmouseout” HTML properties:

<img id='menuImg' src="1.jpg" onmouseover="hover(this);" onmouseout="hoverOut(this)"/>

onmouseover” calls the “hover()” function while, the “onmouseout” event calls the function “hoverOut()”:

function hoverOut(img){
 img.src = "1.jpg"
}

The output shows that the image is successfully changed when the mouse is over the image and it is changed when the mouse is going out of the image:

That was all about the changing image on hover.

Conclusion

For changing the image on hover, use the “onmouseover” event. For toggling effect, use the “onmouseover” attribute with “onmouseout” event. When the mouse/cursor is moved through an element or one of its children, the onmouseover event is triggered, while when the mouse/pointer is moved out of an element, the onmouseout event occurs. In this post, we demonstrated the procedure for changing the image on hover in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.