Reputation: 8402
I have the following code :
$.each(images, function (intValue, currentElement) {
$("#image").on('load', function () {
if (($("#image").width() < 50) || ($("#image").height() < 50)) {
// do something
} else {
// do something
return false; // not working !!!
}
}).attr("src", currentElement).hide()
.each(function () {
if ($(this).complete) $(this).trigger('load');
});
});
i want to break out the each iteration inside else statement, so i add return false
, but it doesn't works, i think because of .on('load', function()....
Upvotes: 0
Views: 434
Reputation: 684
Is this what you are looking for?. In your case why it is not working is image loading is asynchronous process, by the time of image load fires the loop will be completed with all the load events attached and they will fire. In each iteration return false
will not work cause there is no image is loaded yet. fiddle
var imageSources = [
'http://placehold.it/10x10',
'http://placehold.it/25x20',
'http://placehold.it/50x50'
];
var loadImg = function loadImages(images){
$("#image").on('load', function () {
if (($("#image").width() < 50) || ($("#image").height() < 50)) {
debugger;
images.shift();
loadImages(images);
} else {
debugger;
$('#image').attr('src', images[0]);
return false;
}
}).attr("src", images[0]).each(function () {
if ($(this).complete) $(this).trigger('load');
});
}
loadImg(imageSources);
Upvotes: 2
Reputation: 43755
var imageSources = [
'http://placehold.it/10x10',
'http://placehold.it/25x20',
'http://placehold.it/50x50',
'http://placehold.it/100x500'
];
var $myImage = $('#myImage');
var current = 0; //tracks which url is currently loaded
$myImage.load(function() {
//use $(this) if you need jQuery here also
if (this.width < 50 || this.height < 50) {
++current; //update tracker
this.src = imageSources[current]; //load new item
}
});
$myImage.attr('src', imageSources[0]);
var imgs = document.querySelectorAll('img');
for (var i=0; i<imgs.length; ++i) {
addLoadEvents(i);
}
function addLoadEvents(i) {
imgs[i].addEventListener('load', function(e) {
myImgFunction(this, i, e);
});
}
var done = false;
function myImgFunction(elem, i, e) {
//stop functions from running on items that are to be removed.
if (done) { return false; }
//do whatever you want here...use "removeTheRest" for whatever condition the remaining images need to be removed.
if (i > 2) {
done = true;
removeTheRest(i);
}
}
function removeTheRest(i) {
//get rid of the rest of the images
var imgLength = imgs.length;
for (var j=i; j<imgLength; ++j) {
console.log(j);
imgs[j].parentNode.removeChild(imgs[j]);
}
}
Upvotes: 2