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 t
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')
})
});
$('img').mouseover(function(){
var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
$(this).attr("src", newSrc);
});
$('img').mouseout(function(){
var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
$(this).attr("src", newSrc);
});
Whilst looking for a solution some time back, I found a similar script to the below, which after some tweaking I got working for me.
It handles two images, that almost always default to "off", where the mouse is off the image (image-example_off.jpg), and the occasional "on", where for the times the mouse is hovered, the required alternative image (image-example_on.jpg) is displayed.
<script type="text/javascript">
$(document).ready(function() {
$("img", this).hover(swapImageIn, swapImageOut);
function swapImageIn(e) {
this.src = this.src.replace("_off", "_on");
}
function swapImageOut (e) {
this.src = this.src.replace("_on", "_off");
}
});
</script>
<img src="img1.jpg" data-swap="img2.jpg"/>
img = {
init: function() {
$('img').on('mouseover', img.swap);
$('img').on('mouseover', img.swap);
},
swap: function() {
var tmp = $(this).data('swap');
$(this).attr('data-swap', $(this).attr('src'));
$(this).attr('str', tmp);
}
}
img.init();
/* Teaser image swap function */
$('img.swap').hover(function () {
this.src = '/images/signup_big_hover.png';
}, function () {
this.src = '/images/signup_big.png';
});
I was hoping for an über one liner like:
$("img.screenshot").attr("src", $(this).replace("foo", "bar"));