views:

62

answers:

5

I have an animated GIF that plays once (doesn't loop). I would like it to animate when clicked. I tried something like this:

$('#plus').click(function(){
    $('#plus').attr('src','');
    $('#plus').attr('src','img/plus.gif')
    });

With the hope that quickly resetting the src would trigger the animation, but no luck. Anyone know what would do it?

A: 

Have you tried removing the img tag and adding it back again? (never tried it, just an idea)

mdrg
A: 

You could try having a single-frame image (of the first frame of animation) and show/hide each one on click. If you want it to reset back to the single-frame image when the animation is done, you could use setTimeout (with how long the animation is as the length of time) and have it hide the animation and show the static image.

Drackir
+3  A: 

Try adding the image with a randomly generated querystring so it looks like a new image to the browser.

<script language="javascript" type="text/javascript">
function randomString() {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = 8;
    var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    document.randform.randomfield.value = randomstring;
}
$('#plus').click(function(){
    $('#plus').attr('src','img/plus.gif?x=' + randomString())
    });
</script>
adam0101
I just grabbed a random string generator off the internet: http://www.mediacollege.com/internet/javascript/number/random.html
adam0101
Thanks man, you nailed it. But I think my way is easier: `$('#plus').attr('src','img/plus.gif?x='+Math.round(Math.random()*1000));`
Isaac Lubow
Time stamp is better than randomly generated. Also look here ==> http://stackoverflow.com/questions/728616/disable-cache-for-some-images
Peter Ajtai
Unless you can click on the image twice in less than a millisecond,
kennebec
@kennebec - You probably don't want the animation running that many times anyway.
Ryan Kinal
A note: this solution ended up being wrong for me because of the non-trivial delay in loading the GIF made it not-snappy enough to be a working UI effect.
Isaac Lubow
A: 

This is a bit of an alternative approach.

You could export the individual frames as their own images and handle animation via javascript.

It lets you do a couple of cool things. A colleague recently had a little timer animation that was synced to the configurable slideshow interval in our image gallery.

The other thing you get out of this is you could use pngs and have translucent backgrounds.

There's probably a sprite animation library for javascript out there somewhere :)

Koobz
+1  A: 
function refreshSrc(who){
    return who.src= who.src.split('?')[0]+'?='+(+new Date());
}
refreshSrc(document.images[0])

Tart it up with jQuery syntax, if you like.

kennebec