2

I have a series of images like the following

image1.png
image2.png
image3.png
image4.png
…
…
image20.png



secondImg1.png
secondImg2.png
secondImg3.png
secondImg4.png
secondImg5.png
…….
……..
secondImg18.png

I want to load 1 image at a time dynamically.

My js

var index = 1;
var timer = setInterval(function(){playAnime()},200);

function playAnime(){
    $('#holder').attr('src','image/image' + index + 'png')
    index++
}

My codes show the general idea of how it works but I am not sure how to stop the index at 20 and 18 to stop the animation. (I could use if statement to check if it's 20 or 18 but I think there is a better way)

Basically, I want to detect if my app loads image21.png and secondImg19.png and stop because there is no such file or the image is broken. Is this doable? Thanks for the help!

FlyingCat
  • 14,036
  • 36
  • 119
  • 198
  • You can, per the link, use an ajax HEAD request, the load() event, or the error() event bindings to achieve what you are looking for. – BrianH Feb 11 '14 at 21:08

1 Answers1

1

You can use .error() event handler

$('#holder').attr('src', 'image/image' + index + 'png').error(function () {
    //Image does not exists do something
});

From Docs

The error event is sent to elements, such as images, that are referenced by a document and loaded by the browser. It is called if the element was not loaded correctly.

Satpal
  • 132,252
  • 13
  • 159
  • 168