2

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:

HTML

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

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

playGif.js

(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);

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

DBS
  • 9,110
  • 4
  • 35
  • 53
HelloElo
  • 23
  • 5
  • Personally I would use a class or a data tag to mark if it's currently a gif or a png, checking the file extension each time is a bit messy and would break if the image name has a `.` before the extension. – DBS Oct 21 '16 at 14:02
  • 1
    Is your actual code using those names for the imgs ? ... if not the only issue I can see is when the code splits the src for the gif if the path has more than one `.` then the `$imgExt[1]` is useless http://codepen.io/anon/pen/LRrZqx – DaniP Oct 21 '16 at 14:08
  • Possible duplicate of [Stopping GIF Animation Programmatically](http://stackoverflow.com/questions/3688460/stopping-gif-animation-programmatically) – Heretic Monkey Oct 21 '16 at 14:16
  • @MikeMcCaughan no, not, this is var swapping, not really stop gif animation. –  Oct 22 '16 at 11:03

1 Answers1

2

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

It is a simple variable swapping problem:

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

To solve it, you need a temporary variable:

a=1;b=2;
temp=a;a=b;
b=temp;

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.

DaniP
  • 37,813
  • 8
  • 65
  • 74