Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JS to trigger a GIF animation?

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?

like image 367
Isaac Lubow Avatar asked Oct 21 '10 15:10

Isaac Lubow


2 Answers

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>
like image 120
adam0101 Avatar answered Oct 28 '22 05:10

adam0101


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.

like image 32
kennebec Avatar answered Oct 28 '22 05:10

kennebec