1

Different to: Restart an animated GIF from JavaScript without reloading the image

I have a simple animated gif icon which plays once (it does not repeat loop)

I have it inside a DIV. When the user mouse the mouse over the DIV I want to play the GIF. When they move out the DIV turns off. When the move back I want them to play the GIF again - can I use a force cache on jQuery:

HTML:

<div class="datebox magicbox_1" id="date_1">
  <img id="magicimage_1" class="magicimg" src="assets/img/dates/gifpicture.gif" alt=""/>
</div>

jQuery:

    $("#date_1").hover(function () {
        $("#magicimage_1").show();
    }, function () {
        $("#magicimage_1").hide();
    });

// thought about these
/*
var myImg = new Image();
myImg.src = "image.gif?rnd=" + Math.random();
img src="filename.gif?rand=<#?=rand(1,1000);?>" alt=""
*/ 
Community
  • 1
  • 1
TheBlackBenzKid
  • 26,324
  • 41
  • 139
  • 209

1 Answers1

2

I updated the old code to show the images reset. It should be fast since it's already cached.

http://jsfiddle.net/gYmvN/4/

So the new code would be:

$("#date_1").hover(function () {
    //$("#magicimage_1").show();
    $("#magicimage_1").show().attr('src', 'assets/img/dates/1_randomhash-aefgh.gif?rnd=' +Math.random()+'');
}, function () {
    //$("#magicimage_1").hide();
    $("#magicimage_1").hide().attr('src', '');
});

As I want to remove the SRC on hover out.. so it plays fully

TheBlackBenzKid
  • 26,324
  • 41
  • 139
  • 209
Matt
  • 7,049
  • 7
  • 50
  • 77
  • So each time the div boxes are hovered; it will always load the gif image again - I dont mind it redownloading as long as it plays it again.. – TheBlackBenzKid Dec 12 '11 at 12:28
  • I can't use image.src attributes as these images are hidden on the server - they cannot be shown to public (URLs will appear only at certain times) – TheBlackBenzKid Dec 12 '11 at 12:30
  • @TheBlackBenzKid the main thing is just to reset the src attribute. That is what will make it reload. So if you don't need to cache, then simply set the src attribute of the image. So, .attr('src', "image.gif?rnd=" + Math.random()), or whatever you are trying to do there. – Matt Dec 12 '11 at 12:33
  • @TheBlackBenzKid: It won't re-download if you set appropriate caching-headers (`Expires` and `Cache-Control`). – Tomalak Dec 12 '11 at 12:39