Sometimes, we want to reset a GIF animation with JavaScript.
In this article, we’ll look at how to reset a GIF animation with JavaScript.
How to reset a GIF animation with JavaScript?
To reset a GIF animation with JavaScript, we can add a random query string to the end of the image URL.
For instance, we write:
<img src='https://media4.giphy.com/avatars/JulietGlock/S2TkRZ9GyF91.GIF' style='height: 100px'>
to add an animate GIF img element.
Then we write:
const img = document.querySelector('img')
setTimeout(() => {
img.src = `${img.src.replace(/\?.*$/,"")}?x=${Math.random()}`;
}, 2000)
to select the img element with querySelector
.
Then we set the img.src
property to the img.src
plus a new query string that had the x
parameter set to a random number.
We have that in the setTimeout
callback so src
will be changed with a delay.
The animated GIF will start from the beginning when src
is changed.
Conclusion
To reset a GIF animation with JavaScript, we can add a random query string to the end of the image URL.