How to change image on hover JavaScript
Short article on how to change the source of the image <img> tag on hover using 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:
- Use
onmouseover()event to change the image when the mouse hovers over the element. - 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:
Related Posts
Press Shift + Enter for new Line in Textarea
Override default textarea behavior on Enter key press without Shift, prevent new lines, and take custom actions like submitting forms instead. Still allow Shift+Enter newlines.
in vs hasOwnProperty(): Differences in Inherited Properties
The article explains the differences between JavaScript's 'in' operator and 'hasOwnProperty()' method. And also learn the use cases of both in JS.
How to Fix "ReferenceError: document is not defined" in JavaScript
The "ReferenceError: document is not defined" is a common error in JavaScript that occurs when trying to access the `document` object in a non-browser environment like Node.js.
How to Fix the "Cannot Read Property of Undefined" Error in JavaScript
The "Cannot read property of undefined" error occurs when you try to access a property or method of a variable that is undefined in JavaScript.
