Stop a gif animation onload, on mouseover start the activation

denislexic picture denislexic · Apr 28, 2011 · Viewed 132.4k times · Source

I have a page with a lot of GIFs.

<img src="gif/1303552574110.1.gif" alt="" >
<img src="gif/1302919192204.gif" alt="" >
<img src="gif/1303642234740.gif" alt="" >
<img src="gif/1303822879528.gif" alt="" >
<img src="gif/1303825584512.gif" alt="" >

What I'm looking for

1 On page load => Animations for all gifs are stopped

2 On mouseover => Animations starts for that one gif

3 On mouseout => Animation stops again for that gif

I suppose this can be done in Jquery but I don't know how.

Answer

Guffa picture Guffa · Apr 28, 2011

No, you can't control the animation of the images.

You would need two versions of each image, one that is animated, and one that's not. On hover you can easily change from one image to another.

Example:

$(function(){
  $('img').each(function(e){
    var src = $(e).attr('src');
    $(e).hover(function(){
      $(this).attr('src', src.replace('.gif', '_anim.gif'));
    }, function(){
      $(this).attr('src', src);
    });
  });
});

Update:

Time goes by, and possibilities change. As kritzikatzi pointed out, having two versions of the image is not the only option, you can apparently use a canvas element to create a copy of the first frame of the animation. Note that this doesn't work in all browsers, IE 8 for example doesn't support the canvas element.