Search code examples
javascriptjquerygifanimated-gif

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?


Solution

  • 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>