Change Image Source on Mousehover using Jquery

Do you want to change the whole image source when user hovers the mouse on image? You can easily change the image source on mouse hover using jquery.

HTML Code

First specify two image sources in the img tag as shown below. The data-alt-src attribute specifies the source of image on hover. Also give a class to img tag.

<img class="xyz" data-alt-src="/images/image-hover.png" src="/images/image.png" />
<img class="xyz" data-alt-src="/images/image-hover1.png" src="/images/image1.png" />

Now write javascript code that changes the image source on mouse hover and mouse out.

var sourceSwap = function () {
var $this = $(this);
var newSource = $this.data('alt-src');
$this.data('alt-src', $this.attr('src'));
$this.attr('src', newSource);
}

Finally add following jquery code to make it work.

$(function () {
$('img.xyz').hover(sourceSwap, sourceSwap);
});

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s