The error()
method was deprecated in jQuery 1.8. So you should be using on('error',function(){});
instead. But, you still have the issue where the error handler has to be attached before the image load is attempted. So, you can set the img src after you attach the handler.
EDIT: It was bothering me that I didn't have a src in my img tag (invalid HTML), so I found this inspired stack overflow: What's the valid way to include an image with no src?. The src="//:0"
is from there.
HTML:
<a href="#"><img data-src="http://placekitten.com/300/300" src="//:0" /></a>
<a href="#"><img data-src="http://asdf.com/broken.jpg" src="//:0" /></a>
<!-- non valid URL -->
Javascript
$(document).ready(function () {
$('img').on ('error', function () {
$(this).data('error',true);
}).each(function() {
$(this).attr('src',$(this).data('src'));
});
$('a').click(function () {
if($(this).find('img').data('error') == true) alert('Image does not exist!');
return false;
});
});
http://jsfiddle.net/10xjo3of/2/