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
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"));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With