Prithviraj Mitra
Prithviraj Mitra

Reputation: 11812

gif animation play only once onclick and mousedown

I have two images: static and animated. I am trying to play that animated image but only once. After that, it will change to static one.

My Code:

$(document).ready(function () {
    $('#targetDIV_three').bind('click mousedown', function () {
        srcToGif2 = "http://demo.pink-squid.co.uk/christmas/s3.gif";
        $("#divthree_three").attr('src', srcToGif2);
    });
});

Fiddle : http://jsfiddle.net/squidraj/33Sqd/

Currently, it is not stopping after the first animation.


Latest fiddle with single animated loop gif.

http://jsfiddle.net/squidraj/4rC8D/1/

Now can't see the animation though the img src is changing.

Upvotes: 0

Views: 10291

Answers (3)

Pavlo
Pavlo

Reputation: 44889

If you want this animated GIF to be played only once, modify it in Photoshop. Go to Window > Timeline, then select looping options (bottom left corner):

enter image description here

Save for web as GIF and voila!

Upvotes: 8

Milind Anantwar
Milind Anantwar

Reputation: 82231

Working Fiddle

Try This:

$(document).ready(function () {
$('#targetDIV_three').bind('click mousedown', function () {

[].slice.apply(document.images).filter(is_gif_image).map(freeze_gif);

function is_gif_image(i) {
return /^(?!data:).*\.gif/i.test(i.src);
}

function freeze_gif(i) {
var c = document.createElement('canvas');
var w = c.width = i.width;
var h = c.height = i.height;
c.getContext('2d').drawImage(i, 0, 0, w, h);
try {
    i.src = c.toDataURL("image/gif"); // if possible, retain all css aspects
} catch(e) { // cross-domain -- mimic original with all its tag attributes
    for (var j = 0, a; a = i.attributes[j]; j++)
        c.setAttribute(a.name, a.value);
    i.parentNode.replaceChild(c, i);
}
}
      });
});

For getting desired effect you can setTimeout to trigger click event #targetDIV_three

Upvotes: 2

idmean
idmean

Reputation: 14865

Chnage your code to this. A timeout is set to set the old gif again.

$(document).ready(function () {
    $('#targetDIV_three').bind('click mousedown', function () {
        srcToGif2 = "http://demo.pink-squid.co.uk/christmas/s3.gif";
        $("#divthree_three").attr('src', srcToGif2);
        setTimeout(function(){
            $("#divthree_three").attr('src', "http://demo.pink-squid.co.uk/christmas/s3_bg.gif");
        },900);
    });
});

http://jsfiddle.net/33Sqd/2/

Upvotes: 0

Related Questions