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.

7
Leave a Reply

6 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
7 Comment authors
  Subscribe  
newest oldest
Notify of
Craigwell

is this how it should look in my HTML page?

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

jef

This is so elegant. Thank you!

Jer

Genious!

Roy Hasidim

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

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 :)