Start/stop gif on mouseover and mouseout

Viewed 61

I am trying to begin a GIF animation when the visitor hovers the image, and I have actually done that part with:

$(document).ready(function() {
  $(".lazy[title='img-static']").hover(function() {
    $(this).attr("src", "https://www.website.com/wp-content/uploads/img-static.png");
  }, function() {
    $(this).attr("src", "https://www.webco.dk/wp-content/uploads/img-animation.gif");
  });
});

It changes the image from the static PNG to the animating GIF, however I need it to switch back to the static when the mouse leaves.

Also I heard that I should have the GIF preload, how would you do that?

Thanks for your help.

1 Answers

Try with mouseenter()/mouseleave() instead, something like:

$(".lazy[title='img-static']").mouseenter(function() {
    $(this).attr("src", "https://www.website.com/wp-content/uploads/img-static.png");
});
$(".lazy[title='img-static']").mouseleave(function() {
    $(this).attr("src", "https://www.webco.dk/wp-content/uploads/img-animation.gif");
});
Related