Cross browser animated gif on hover and reverse mouse movement

I have the following images:

Static image | Running animation | Completion animation

And I use the following code ( jsfiddle example ):

$(function() { $("#link-gif").hover( function() { /* starting animation */ $(this).css("background-image", "url('http://i.imgur.com/HhsBws5.gif')"); }, function() { /* ending animation */ $(this).css("background-image", "url('http://i.imgur.com/WLFzz3S.gif')"); } ); }); 
 #link-gif { width:150px; height:40px; border:1px solid #39464E; background-image:url('http://i.imgur.com/YgLJoVH.png'); /*static*/ background-size:contain; background-repeat:no-repeat; background-position:bottom center; cursor:pointer; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="link"> <div id="link-gif">&nbsp;</div> </div> 

So, in general, I want this to happen: I first upload a static image. When someone hovered over #link-gif , the starting gif animation starts, and when you hover it to the left, the ending animation starts.

For some reason, when you hover over an image, the image is not animated. It just comes to the end of the gif. Does anyone know why this is happening?

+8
javascript jquery html css animation
source share
1 answer

This is because the image is cached. Try adding a dynamic value to the end of the gif, like time. Check out the changes I made to the code. I added the current time to the img path.

 $(function() { $("#link-gif").hover( function() { /* starting animation */ var url = "url('http://i.imgur.com/HhsBws5.gif?time=" + new Date().getTime() + "')"; $(this).css("background-image", url); }, function() { /* ending animation */ var url = "url('http://i.imgur.com/WLFzz3S.gif?time=" + new Date().getTime() + "')"; console.log(url); $(this).css("background-image", url ); } ); }); 
 #link-gif { width:150px; height:40px; border:1px solid #39464E; background-image:url('http://i.imgur.com/YgLJoVH.png'); /*static*/ background-size:contain; background-repeat:no-repeat; background-position:bottom center; cursor:pointer; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="link"> <div id="link-gif">&nbsp;</div> </div> 
0
source share

All Articles