8

Im wondering if its possible to have an animated gif play, then fire off an event through jquery once the gif has reached the end of its animation. Once it does that, then it loops back to the beginning of the queue, and plays the gif then event again.

If you take a look at my jfiddle, i made a little gif of a guy typing. and then when he looks up and gets an idea, i want that "thought" div to change to something else. I pretty much want that word above his head to be in synch and change right when his head pops up.

http://jsfiddle.net/mMVhK/1/

<div id="thought">
    Amazing Idea
</div>

<div id="firstgif">
    <img src="http://i.imgur.com/pcc4DP5.gif"/>
</div>
kingkelly
  • 199
  • 1
  • 1
  • 8

1 Answers1

5

My answer to this is similar to this answer and this one on a similar stackoverflow question.

If you have a GIF with a set number of frames and without loop, you can make javascript use setTimeout to trigger your event. With this though, it has a very high chance of going out of sync simply because you are playing a guessing game whether the rendering of the GIF will play out at the same speed as the javascript execution each time.

A safer option is what the other answer I linked said in the way that you use a sprite map to simulate an animation. This is achieved by using javascript to change the background position of the image in the element. This way, you have a lot more control about how the animation animates, greater control over javascript events and better timing as it is tied to javascript execution speed / it will only be at the frame of the animation you tell it to be at.

I don't have an example however I am happy to help if you get a decent headstart on this or have any other questions.

Useful information regarding CSS Sprites

Community
  • 1
  • 1
Turnerj
  • 4,258
  • 5
  • 35
  • 52
  • what do you mean without a loop? how can it not have loop? – vsync Sep 29 '14 at 14:33
  • When you create a gif, you normally have the option to control whether the animation loops/repeats. For what I proposed with using `setTimeout`, it would be best/easiest if the image did not have a loop as you need the animation to stop at a specific spot. (Other alternatives if you cant do that is switching the animated gif for a static end frame once the timeout fires) – Turnerj Sep 30 '14 at 00:31
  • setTimeout is no guarantee the gif has loaded and it ended "playing" – Roko C. Buljan Aug 30 '19 at 22:29
  • @RokoC.Buljan In terms of checking if the gif has loaded, you can listen on the `onload` event. While I don't know a way to actively know when it finishes "playing", my comment relates to knowing in advance how long the animation plays for and setting the timeout to that specifically. `setTimeout` may not guarantee exactly X ms, it does guarantee _at least_ X ms so with a non-looping gif, worst case is it waits a short amount of time on that final frame. – Turnerj Sep 02 '19 at 05:09