Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - replace image on hover

Tags:

jquery

I have an images folder. Within this folder, I have several images of two types; one png and one gif. The displayed image is the png version. On an image hover, I need to replace it with its gif version. And when hover is out, put the png version back in place.

I currently have the following which works

$(".image-container").mouseover(function () {
    var imgName = $(this).find('img').attr('src');
    var img2 = imgName.substring(0, imgName.lastIndexOf("."));
    $(this).find('img').attr("src", img2+".gif");
}).mouseout(function () {
    var imgName = $(this).find('img').attr('src');
    var img2 = imgName.substring(0, imgName.lastIndexOf("."));
    $(this).find('img').attr("src", img2+".png");
});

It works, but I dont like the way I am repeating things. Is there any way to make this more efficient?

Thanks

like image 330
katie hudson Avatar asked Jan 13 '16 13:01

katie hudson


1 Answers

I would say, use data-* attributes in a better way. I would suggest you to have something like this:

<img src="img.png" data-src="img.png" data-hover="img.gif" alt="" class="image-container" />

And in the jQuery:

$(".image-container").mouseover(function () {
  $(this).attr('src', $(this).data("hover"));
}).mouseout(function () {
  $(this).attr('src', $(this).data("src"));
});

Or in short, you can also use .replace(). You don't need regex for this simple replacement:

$(".image-container").mouseover(function (e) {    
    $(this).attr("src", $(this).attr("src").replace(".png", ".gif"));
}).mouseout(function (e) {
    $(this).attr("src", $(this).attr("src").replace(".gif", ".png"));
});
like image 195
Praveen Kumar Purushothaman Avatar answered Sep 30 '22 14:09

Praveen Kumar Purushothaman