in order to not make the html file too heavy, and for simple and fast reading porpuses, I wanted to create img
elements "dynamically" but only if they exist in the server, that's what I exptect as result, so I tried bother the two solutions here : Question
the solution of error()
mehode doesn't work : Demo
the console says $(...).error
is not a function, I don't know why
I tried to use a flag
$('ul').each(function() {
for (i = 2; i < 10; i++) {
var flag = true
image = new Image()
image.src = $(this).find('img').attr('src').replace(/\d/, i)
$(image).error(function() {
flag = false
})
if (flag /*or i can just write: flag==true*/ ) {
//do nothing
} else {
$(this).append('<li>' + $(image) + '</li>')
}
//or just => flag ? return : $(this).append('<li>' + $(image) + '</li>')
}
})
but it doesn't work with all the options I tried I also tried to not use .error()
and just use if(image.width!=0)
or if($(image).width()!=0)
but none of them work, when I try to get the width in the console either it says 0 (for first option) or undefined
the second solution of Ajax doesn't work either : Demo
I don't know if success
is the right parametre to use, I checked the documentation in jquery website, and it's the only parameter that makes sens to me for this matter
I think there are a lot of mistakes I did, please guide me thanks in advance
jQuery doesn't really have a .error()
method (it was deprecated in 1.8), it's the native image.onerror
, but jQuery will support it if you do $(image).on('error', function() {...
.
But why not use the image.onload
event instead
$('ul').each(function(index, elem) {
for (var i = 2; i < 10; i++) {
(function(image) {
image.onload = function() { // image loaded successfully
$(elem).append( $('<li />').append(image) );
}
image.src = $(elem).find('img').attr('src').replace(/\d/, i);
})(new Image());
}
});
You need to use onerror, for example:
function checkImage(src, good, bad) {
var img = new Image();
img.onload = good;
img.onerror = bad;
img.src = src;
}
var imageExist = "http://jsfiddle.net/img/logo.png";
var imageNotExist = "foo.gif";
checkImage(imageExist, function() {
alert(this.src + " " + "good");
}, function() {
alert("bad");
});
checkImage(imageNotExist, function() {
alert("good");
}, function() {
alert(this.src + " " + "bad");
});
</div>