28Jun

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();

Tada!

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

Subscribe
Notify of

7 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Craigwell
9 years ago

is this how it should look in my HTML page?

img.src = “your_image_url.gif”+”?a=”+Math.random();

jef
9 years ago

This is so elegant. Thank you!

Jer
7 years ago

Genious!

Roy Hasidim
5 years ago

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 =
`url(‘${preFix}/ImagePath.gif?a=${Math.random()}’)`;
//console.log(loaderGifUrl); (to check the given url is right);
document.querySelector(‘.loader’).style.background = `#fff ${loaderGifUrl} no-repeat 50% 50%`;
};
loaderMaker();

5 years ago

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
});

Hey Thomas, thank you for that! Your code resolved my problem :)