Control animated gif with Javascript/Jquery

Hi guys,

I have a client who’s given me an animated gif to use as a logo. they want the animation to play on page load and also on mouseover.

I’ve got this working, but if the user mouses over, then mouses out and then mouses over the gif again the animation starts again even if the original animation hasn’t finished.

The animation takes about 5 seconds, is there a way to sleep() the code until the first animation finishes before accepting further invocations to run?

In other words:
a) user mouses over the animation gif - animation starts
b) user mouses out (animation still running)
c) user mouses in again (animation still not finished) - HERE THE ANIMATION WOULD START AGAIN BUT I DON’T WANT IT TO UNLESS IT FINISHED ITS CYCLE FROM a) FIRST!

Thanks in advance to any who can assist!

by the way here’s my code:


$(function() {
		$("#logo").hover(
		  function () { //MOUSEOVER - reset the image src thus reloading the image and running the animation again
		    $(this).attr('src', 'images/animated.gif');
                    //sleep(5) - I NEED THE SCRIPT TO 'FREEZE' HERE UNTIL THE ANIMATION IS DONE
		  },
		  function () { //MOUSEOUT - do nothing	
		  }
		);
	});

I am not aware of any way to control animated gifs with javascript. They just run until the end.

One way to overcome your problem is to use a program like ImageReady to unbundle the static images in the animated gif and then run them in a javascript animation instead. This should be OK for a 5 second cycle although the practicality of doing this will depend on how many images are involved. You can then turn it on or off as you like.

Another way to solve the problem is to prevent the mouseover working while the gif is running. This might be a little inaccurate, because you would need to time it as there is no other way of knowing when the gif is finished its cycle. One possibility is using a flag like “running=true” and then testing for this when you handle the mouseover event. I often use this method like this: if(running==true){ return; }.

Another way to do it is to move a <div> cover over the animated gif so that the mouseover event cannot be accessed. This works fine if you use a cover z-index which is higher than the z-index of the layer containing the mouseover link. After the gif is finished you can move it down below the mouseover and it works again.