How to replay an animated gif in javascript

I had the problem to have a gif always loaded to the final step. The non-looping animated gif didn’t replay when the page was reloaded. Even when I was using “image.src” in javascript. Here is a quick trick to force replay a gif or reset it using js.

To  reset or replay an animated GIF you can append a random query string in the url

// reset a gif in javascript
img.src = "your_image_url.gif"+"?a="+Math.random();


Please note, that means that the GIF will be downloaded every time so keep it a small file.

7 thoughts on “How to replay an animated gif in javascript

  1. amazing!
    here is a solution for using background image – can be used for img also with tiny changes:

    const loaderMaker = () => {
    const preFix = window.origin;
    const loaderGifUrl =
    //console.log(loaderGifUrl); (to check the given url is right);
    document.querySelector(‘.loader’).style.background = `#fff ${loaderGifUrl} no-repeat 50% 50%`;

  2. Sorry to be late to the conversation but here is my solution.

    In the HTML body:

    In the JavaScript (I’m using jQuery):
    $(document).ready(function() {
    $(‘#alogo’).attr(‘src’, ‘images/NB.gif’);
    // Other startup code

Leave a Reply