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:
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:
{
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:
“onmouseover” calls the “hover()” function while, the “onmouseout” event calls the function “hoverOut()”:
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.