I have tried this code copied from jQuery site, but it fails in IE7/IE8, but works in other browsers. What is wrong with this code, it's from jQuery site(http://api.jquery.com/error/). I'm using jQuery version 1.4.4.
$(document).ready(function(){
$("img").error(function(){
$(this).hide();
});
});
Step 1: Reference the image as an object instead of an img. When objects fail they don't show broken icons; they just do nothing. Starting with IE8, you can use object and img tags interchangeably. You can resize and do all the glorious stuff you can with regular images too.
To show or hide an image with JavaScript, we can set the style. visibility property of the img element. to add buttons and img elements.
The hidden attribute hides the <img> element. You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <img> is not visible, but maintains its position on the page.
The problem is that by the time $(document.ready)
is executed, the image has already finished loading so the load/error events won't be triggered anymore.
The only way I can think of to bypass this is to reload the image, thus "force" the event to be triggered:
$(document).ready(function(){
$("img").each(function(index) {
$(this).error(function() {
$(this).hide();
});
$(this).attr("src", $(this).attr("src"));
});
});
It shouldn't be too bad on performance as the images will be taken most probably from the cache, not really reloaded from the server.
Live test case (with cool cats ;)) is available here: http://jsfiddle.net/yahavbr/QvnBC/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With