Reputation: 181
Using jQuery, I've been able to swap images on hover and change it back on mouseout.
I have 2 images, image1 and image2. image1 is the original image, when hovered mouse2 should be shown and should remain even on mouseout. on the next hover, the original image replaces image2 and so on...
I've tried 2 codes. The first one changes the image back on mouseout. The second one, nothing happens even on initial hover.
Code 1
$(document).ready(function () {
$("#img1").hover(function () {
if ($(this).attr('src') == 'www.domain.com/image1.jpg') {
$(this).attr('src','www.domain.com/image2.jpg');
} else if ($(this).attr('src') == 'www.domain.com/image1.jpg') {
$(this).attr('src','www.domain.com/image1.jpg');
}
});
});
Code 2
$(document).ready(function () {
$("#img1").hover(function () {
if ($(this).attr('src') == 'www.domain.com/image1.jpg') {
$(this).attr('src','www.domain.com/image2.jpg');
}
if ($(this).attr('src') == 'www.domain.com/image1.jpg') {
$(this).attr('src','www.domain.com/image1.jpg');
}
});
});
Help would be greatly appreciated.
Thanks!
Upvotes: 0
Views: 132
Reputation: 18584
Try this:
$("#img1").on('mouseenter', function () {
if ($(this).attr('src') == 'www.domain.com/image1.jpg') {
$(this).attr('src','www.domain.com/image2.jpg');
} else if ($(this).attr('src') == 'www.domain.com/image2.jpg') {
$(this).attr('src','www.domain.com/image1.jpg');
}
});
As per my comment, you do not have use the .hover()
shortcut, just bind the mouseenter
event.
Edit: I also fixed the else if
part, but I leave the code optimization to you.
Upvotes: 2
Reputation: 888283
As the documentation clearly states, the hover
function adds a handler to both mouseenter
and mouseleave
.
If you only want to handle mouseenter
, don't do that.
Upvotes: 1