Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Change the image source on rollover using jQuery

I have a few images and their rollover images. Using jQuery, I want to show/hide the rollover image when the onmousemove/onmouseout event happen. All my image names follow the same pattern, like this:

Original Image: Image.gif

Rollover Image: Imageover.gif

I want to insert and remove the "over" portion of image source in the onmouseover and onmouseout event, respectivel
by

2 Answers

akshay1995
To set up on ready:

$(function() {
$("img")
.mouseover(function() {
var src = $(this).attr("src").match(/[^\.]+/) + "over.gif";
$(this).attr("src", src);
})
.mouseout(function() {
var src = $(this).attr("src").replace("over.gif", ".gif");
$(this).attr("src", src);
});
});

For those that use url image sources:

$(function() {
$("img")
.mouseover(function() {
var src = $(this).attr("src");
var regex = /_normal.svg/gi;
src = this.src.replace(regex,'_rollover.svg');
$(this).attr("src", src);

})
.mouseout(function() {
var src = $(this).attr("src");
var regex = /_rollover.svg/gi;
src = this.src.replace(regex,'_normal.svg');
$(this).attr("src", src);

});
});
sandhya6gczb
If you have more than one image and you need something generic that doesn't depend on a naming convention.

HTML

<img data-other-src="big-zebra.jpg" src="small-cat.jpg">
<img data-other-src="huge-elephant.jpg" src="white-mouse.jpg">
<img data-other-src="friendly-bear.jpg" src="penguin.jpg">

JavaScript

$('img').bind('mouseenter mouseleave', function() {
$(this).attr({
src: $(this).attr('data-other-src')
, 'data-other-src': $(this).attr('src')
})
});

Login / Signup to Answer the Question.