Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-Browser animated gif on hover & reverse when mouse leaves

I have the following images:

Static Image | Starting Animation | Ending Animation

And I am using 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 summary, what I want to happen is: I first load the static image. When someone hover's over the #link-gif, the starting animation gif starts, and when you hover off of it, the ending animation starts.

For some reason, when you hover over the image, the image doesn't animate. It just goes to the end of the gif. Does anyone know why this would be happening?

like image 346
bryan Avatar asked Mar 01 '16 20:03

bryan


1 Answers

This happens because the image is cached. Try adding some dynamic value at the end of the gif, like the time. Check the modifications I made at your code. I added current time at 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>
like image 84
Roumelis George Avatar answered Oct 05 '22 13:10

Roumelis George