Sorry but, I've had a look at similar posts on Stack Overflow and could not find my exact situation.
I'm iterating on a bunch of images and I want to exit as soon as I find the one meeting my specifications. Trouble is, I need to use an 'onload' event to test that.
I don't know how to break out of my innermost function: the each() loop always iterates on all items, even though the second image fits the bill. Here's the jsfiddle: you will see 3 alerts, one for each iteration. http://jsfiddle.net/q07awnbr/10/
If anyone could guide me, that would be awesome! Thx.
// A bunch of images
var arrImages = ["http://i.imgur.com/cKUVXuQ.jpg","http://i.imgur.com/Ei598tR.jpg","http://i.imgur.com/W92PhqU.jpg"];
// Iterate until I find the first one meeting my specs
$.each(arrImages, function(i,item)
{
extension = item.slice(-(3)).toLowerCase();
if (extension == "jpg")
{
// Test image size
newImg = new Image();
newImg.onload = function()
{
if (this.width > 600 && this.height > 900)
{
// All right! That's the one. Set it as src on my web page
$("#MyImgBg").attr("src",this.src);
return false; // trying to break out - not working
}
};
newImg.src = item;
}
// I expected this alert to popup only twice
alert(i);
});