Change Image on Mouse Hover Tutorial

Change Image on Mouse Hover Tutorial


We will keep this tutorial short and focused on how to change an image on hover.

You must have seen it in several websites and blogs that when you hover your mouse pointer on an image-link then the image changes.

Do you understand what I’m talking about? Well, place your mouse pointer over the image provided below.

IMAGE CHANGE ON HOVER : DEMO

Image on left side is a link.
Image on left side is not a link.

HTML Syntax used in Image Change Demo Above

The HTML code used in the above two demo examples respectively are :

WITH LINK :

<a href="http://www.techpuffs.com/8731/change-image-on-mouse-hover-in-html-with-onmouseover-and-onmouseout/"><img onmouseover="this.src='http://www.techpuffs.com/easy-media/image-change-color.png'" onmouseout="this.src='http://www.techpuffs.com/easy-media/image-change-black.png'" src="http://www.techpuffs.com/easy-media/image-change-black.png" /></a>

WITHOUT LINK :

<img onmouseover="this.src='http://www.techpuffs.com/easy-media/image-change-color.png'" onmouseout="this.src='http://www.techpuffs.com/easy-media/image-change-black.png'" src="http://www.techpuffs.com/easy-media/image-change-black.png" />

HTML Syntax to Change Image on Hover

Viewing the above code we can understand that the code for achieving the required result should be :

WITH LINK :

<a href="LINK URL"><img onmouseover="this.src='SECOND IMAGE URL'" onmouseout="this.src='FIRST IMAGE URL'" src="FIRST IMAGE URL" /></a>

WITHOUT LINK :

<img onmouseover="this.src='SECOND IMAGE URL'" onmouseout="this.src='FIRST IMAGE URL'" src="FIRST IMAGE URL" />

The described effect can also be achieved through CSS styling, but why use CSS when it can be directly achieved through simple HTML.

Use properly single (‘) and double (“) quotes in this tutorial. Also use images of same dimensions (same width and same height) for smooth effect.