title: play/stop gif on click using javascript
body: <p>I want a gif to play when clicked, and to stop when clicked again. I'm following this method: <a href="http://www.hongkiat.com/blog/on-click-animated-gif/" rel="nofollow">http://www.hongkiat.com/blog/on-click-animated-gif/</a></p>
  
  <p>So far, I have:</p>
  
  <p>HTML</p>
  
  <pre><code>&lt;figure&gt;
   &lt;img src="test.png" alt="Static Image" data-alt="test.gif"/&gt;
  &lt;/figure&gt; 
  
  &lt;script src="playGif.js" type="text/javascript"&gt;&lt;/script&gt;
  </code></pre>
  
  <p>playGif.js</p>
  
  <pre><code>(function($) {  
      // retrieve gif
      var getGif = function() {
          var gif = [];
          $('img').each(function() {
              var data = $(this).data('alt');
              gif.push(data);
          });
          return gif;
      }
      var gif = getGif();
  
      // pre-load gif
      var image = [];
      $.each(gif, function(index) {
          image[index]     = new Image();
          image[index].src = gif[index];
      });
  
      // swap on click
      $('figure').on('click', function() {
          var $this   = $(this),
              $index  = $this.index(),
              $img    = $this.children('img'),
              $imgSrc = $img.attr('src'),
              $imgAlt = $img.attr('data-alt'),
              $imgExt = $imgAlt.split('.');
  
          if($imgExt[1] === 'gif') {
              $img.attr('src', $img.data('alt')).attr('data-alt', $imgSrc);
          } else {
              $img.attr('src', $imgAlt).attr('data-alt', $img.data('alt'));
          }
      });
  })(jQuery);
  </code></pre>
  
  <p>Instead of swapping the content of src and data-alt, this only puts data-alt into src, and data-alt remains the same.</p>
  
  <p>The gif does play on click, but if clicked again it reloads the gif instead of reverting to the png (at least in Chrome and Firefox. IE just does nothing on further clicks).</p>