Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restart animated GIF as background-image

Tags:

Is it possible to restart an animated GIF used as background-image?

Consider this HTML:

<div id="face">     <div id="eyes"></eyes> </div> 

And this style:

#eyes.blink {     background-image:url('blink.gif'); } 

I would like the blink.gif animation to play every time I add the class blink to #eyes, not just the first time.

I expected this to work:

function startBlink() {     $('#eyes').addClass('blink'); }  function stopBlink() {     $('#eyes').removeClass('blink'); } 

The problem is that both Firefox and WebKit browser do not play a background-image GIF animation again once it has played once. Adding/removing the class blink only works the first time.

like image 844
hpique Avatar asked Sep 27 '11 12:09

hpique


People also ask

Can you use a GIF as an overlay?

To make GIFs overlay images, the process is nearly the same. Just make sure the GIF has a transparent background so it can appear with the image behind it. Then add the still image to your Layers panel below the grouped GIF image, and it will appear behind the GIF.

Can you save a GIF with a transparent background?

Preserve background transparency in a GIF or PNG imageOpen or create an image that contains transparency, and choose File > Save For Web. In the Save For Web dialog box, select GIF, PNG‑8, or PNG‑24 as the optimization format. Select Transparency.


1 Answers

You can get the animated gif to replay by reloading it. This isn't ideal for bandwidth, especially if your image is large, but it will force a restart of the animation.

In my example I'm adding and removing it onclick of <div id="animated">:

$('#animated').click(function() {      /* Reference to the clicked element and toggle the .go class */     var $div = $(this);     $div.toggleClass('go');      /* Start the animated gif */     if ($div.hasClass('go')) {          /* Create an <img> element and give it the animated gif as a src.  To             force a reload we add a date parameter to the URL */         var img = document.createElement('img');         img.src = "http://yoursite.com/animated.gif?p" + new Date().getTime();          /* Once the image has loaded, set it as the background-image */         $(img).load(function(){             $div.css({backgroundImage: "url("+img.src+")"});         });      /* Remove the background-image */             } else {        $div.css({backgroundImage: "none"});     } }) 

Demo of it in action.

like image 96
Pat Avatar answered Sep 18 '22 15:09

Pat