Elliott C. Back: Internet & Technology

Animated Gif Stops with Javascript / Click?

Posted in Browsers, Code, Interface, Javascript, Microsoft by Elliott Back on November 3rd, 2008.

If you’ve ever tried to get an animated .gif file to continue playing in IE after a link is clicked, javascript runs for a form submit, or the window.location is set to a new URL, then you’ve probably already gone through the phases of frustration, and come straight to Google.

Here’s the setup. You’ve got a piece of javascript redirecting the user on a click (yes, I know this is a bad idea). Hopefully you got this from a legacy app:

<script language="javascript"><!--
function go(href) {
     $('spinner').style.display = '';
     location.href = href;
}
//--></script>
<a href="defaultAction.htm" onClick="go(this.href);return false">go</a>

Internet Explorer stops animated gifs when there is a javascript event, so if you try this code, it’s going to fail dramatically. What you need (for IE6 and IE7) is a hack:

<script language="javascript"><!--
function go(href) {
     $('spinner').style.display = '';
     location.href = href;
     $('spinner').src = $('spinner').src;
}
//--></script>
<a href="defaultAction.htm" onClick="go(this.href);return false">go</a>

Yes, reassigning the src attribute of an img will cause the image to keep animating, even when in the process of loading the next page. Note–this doesn’t work as well in Firefox. For that, you should either (a) upgrade the application to load data through AJAX, not URL redirection, or (b) use an iframe pointing to the image.

PS, if you need some ajax loading indicators, there’s a bunch!