Activate Animated GIF onclick

I have a GIF image with 18 frames. I set it to not loop.

How can I set it so that it runs one loop when someone clicks on it, and each time they click on it?

I tried this but it did not work:

<img src="images/cust/animated-800-noloop.gif" alt="" class="post-thumb" onclick='javascript:(this.src=="images/cust/animated-800-noloop.gif"?this.src=""images/cust/animated-800-noloop.gif":"")'/>		

src will contain the absolute address, so the comparison will fail.

Try:


<img src="images/cust/animated-800-noloop.gif" alt="" class="post-thumb" onclick='this.src=this.src'/>

maartenvr, you cannot trigger an animated GIF’s animation within the page. The only way you could technically achieve the effect would be to embed the image within an iFrame and then have the link reload the page (causing the animation to reoccur) through the target attribute. It’s deprecated and it’s pretty ugly, but it would do the job. This is another downside of GIF animation, it has no event triggers or method of calculating when an animation should work. :slight_smile:

Could you have a static image shown and preload the animated gif?
Then you can switch the static gif with the animated one, couldn’t you?

Technically you could have an animated GIF sprite which has a static version against an animated one which never changes and then trigger the effect on rollover, though the OP wanted it onclick, and the only way to cause that effect would be through CSS3 selectors (via anchors) to denote the change. And the problem with that (using the target attribute) is that it would only work on the initial click… that and it’s totally unsupported by Internet Explorer. :slight_smile:

If you know exactly how long the animation lasts, you could also have a setTimeout that replaces the animated version with the static one once the animation is finished. Then you can repeat the process when the user clicks the image. GIFs have a “loop times” property which you can set to 1 to effectively stop it from looping. Then it’s a simple case of swapping images. If the first frame in the GIF is identical to the last, then you don’t even need a static image after the first run and you just need to set the src to the same thing again (this.src = this.src).

Not really, JavaScript can handle this easily by preloading the image, using event listeners and swapping the src attribute.

Well… the code that Logic Ali gave actually works like a charm!

Click on the screwdriver halfway down the page on http://www.promodriver.com

Even in IE it works… The funny thing is that in IE it loops twice, and in FF once.

That’s unrelated to the script reload, it’s just the way I.E. animates that image. If you load the image directly into IE, the animation runs twice:

http://www.promodriver.com/images/cust/animated-trans.gif