Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On mouse hover, change picture in JavaScript

I have an image in my HTML code, and I want to make it so that when my mouse is hovering over the image, it will change to the other image, and when the mouse is not hovering over the image, it switches back to the default. How do I program this in a <script> tag?

like image 425
Anonymous Avatar asked Nov 16 '25 01:11

Anonymous


1 Answers

No <script> tag necessary. Use onmouseover and onmouseout to change the image source.

onmouseover will execute an action when your mouse goes over the image. In this case, we use this.src to set the image src to another image.

onmouseout will execute an action when your mouse goes out of the image. In this case, we use this.src again to set the image to the default image.

<img title="Hello" src="https://static.independent.co.uk/s3fs-public/thumbnails/image/2017/09/12/11/naturo-monkey-selfie.jpg?w968h681" onmouseover="this.src='https://www.ctvnews.ca/polopoly_fs/1.4037876!/httpImage/image.jpg_gen/derivatives/landscape_1020/image.jpg'" onmouseout="this.src='https://static.independent.co.uk/s3fs-public/thumbnails/image/2017/09/12/11/naturo-monkey-selfie.jpg?w968h681'" />
like image 87
Aniket G Avatar answered Nov 17 '25 18:11

Aniket G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!