2

I have the .gif set to loop only once and I used this tiny code to activate it on click:

<img src="bird.gif" onclick='this.src=this.src'/>

The problem, is, the gif currently plays when the page loads, which I don't want. I need the image to remain static until clicked.

I could just swap a static image out with the animated one, using this:

<img src="bird2.gif" onclick="changeImage(this)" />
<script>
 function changeImage(element) {
     element.src = element.bln ? "bird2.gif" : "bird.gif";
     element.bln = !element.bln;
 }
</script>

But then you'd have to click it twice before it will play again (like an on/off switch), which is kinda clunky and less desirable.

Does anyone have any solutions? Need it to be static on load, and then it will play every time it is clicked. Thanks

edit: These answers seem like the solution, but they're not working for me. The images are remaining static. I don't know what everyone else sees on their screens but I'm running in Chrome and it's just still after clicking or mousing over.

chils
  • 63
  • 1
  • 10
  • possible duplicate of [Stop a gif animation onload, on mouseover start the activation](http://stackoverflow.com/questions/5818003/stop-a-gif-animation-onload-on-mouseover-start-the-activation) – JKirchartz Apr 20 '15 at 17:19
  • When a page loads, the static image shows on the page. When a user clicks on this static image, the static image swaps with an animated GIF. If the animated GIF plays once or up to N times and it has not finished playing, and the user clicks the “image” again, should the animated GIF stop? Should “stop” mean that the static image replaces the animated GIF again? If the animated GIF reaches the end – no more frames from the animated GIF to show – should the static image replace the animated GIF automatically? – John Frederick Chionglo Apr 21 '15 at 04:43
  • The static image does not have to replace the animated gif automatically, if possible. Since I cannot control animation on the gif itself I'd have to somehow determine when the gif comes to its natural end (when there are no more frames). If the animation has not ended and the user clicks the image again, the animation should restart. – chils Apr 24 '15 at 04:47

2 Answers2

1

You can't control gif animations with javascript that I'm aware of. A good idea would be to have 2 images. One being a static image and one being the actual gif that plays when you click it. It would look something like this (untested)

HTML

<img id="bird" src="bird.png"/>

jQuery:

var bird = $('#bird'),
    bird_gif = '/path/to/bird.gif';

bird.click(function() {
    bird.src = bird_gif;
});

Pure javascript:

var bird = document.getElementById('bird'),
    bird_gif = '/path/to/bird_gif';

bird.onclick = function() {
    bird.src = bird_gif;
}
Walker Boh
  • 750
  • 6
  • 13
0

Inside your changeImage function you can call setTimeout to make the image swap back to the static version when the animation is complete.

dcabines
  • 112
  • 4