Reputation: 9369
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('https://i.sstatic.net/14qMg.gif')");
},
function() {
/* ending animation */
$(this).css("background-image", "url('https://i.sstatic.net/npwJ0.gif')");
}
);
});
#link-gif {
width:150px;
height:40px;
border:1px solid #39464E;
background-image:url('https://i.sstatic.net/W4Kgi.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"> </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?
Upvotes: 10
Views: 2716
Reputation: 6746
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"> </div>
</div>
Upvotes: 1