JavaScript Demo - Pseudo Controls for Animated GIFs
Return to the JavaScript Demos Page

Let's say you have an animated GIF and you want to be able to stop and restart the animation. JavaScript can't do this, as the animation frames of the GIF are not exposed to the DOM and thus are inaccessible to JavaScript. You could use something somewhat complicated like jsgif, but this involves having to send the GIF to a server where it is parsed into pieces and then gets displayed using the HTML5 canvas feature with controls for the animation frames. If this meets your needs, use it, but keep in mind that it doesn't work if a user's browser does not support the HTML5 canvas.
One very simple way to accomplish the appearance of control is to use JavaScript to switch between two GIFs. One GIF contains the animation, while the other GIF contains just one frame of the image (or anything else you may want to display). Stopping the animation then involves switching to the one-frame "stopped" GIF and playing the animation again similarly involves switching back to the animated GIF. Be aware that this means the stop control doesn't necessarily "stop" on the actual frame being displayed, but for many purposes this doesn't matter.
This demo uses user-controlled buttons with JavaScript code to stop and start the animation, but any JavaScript-controlled functionality can be used: mouse events on the image or anything that supports mouse events, for example.