HelloElo HelloElo - 1 year ago 231
Javascript Question

play/stop gif on click using javascript

I want a gif to play when clicked, and to stop when clicked again. I'm following this method: http://www.hongkiat.com/blog/on-click-animated-gif/

So far, I have:


<img src="test.png" alt="Static Image" data-alt="test.gif"/>

<script src="playGif.js" type="text/javascript"></script>


(function($) {
// retrieve gif
var getGif = function() {
var gif = [];
$('img').each(function() {
var data = $(this).data('alt');
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'));

Instead of swapping the content of src and data-alt, this only puts data-alt into src, and data-alt remains the same.

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).

Answer Source

So here is the finished jsfiddle: https://jsfiddle.net/2060cm1c/

It is a simple variable swapping problem:

a=b;// now a=2
b=a;// a=2, b=a=2

To solve it, you need a temporary variable:


Now solve the OP's problem:

var temp=$img.attr('src');
$img.attr('src', $imgAlt).attr('data-alt', temp);

So, the problem is as easy as swapping 2 variables. You don't need the if to check the extension.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download