Want to hide the image if the image is not found in the src location?

jQuery('img').bind('error',function(){
            alert('hi');
        jQuery(this).hide(); 
        });

I wrote this code, but inaccessible images are not hidden and still show a cross sign. Someone may point out what might be wrong. I write this in the document.ready document, and I tried it also in the window.onload window.

+5
source share
7 answers

The problem is that by the time you bind the error event, the onerror image is already running. You can run it again by resetting img.src after binding the event. The following steps were performed in IE8, FF, and Chrome.

$('img').error(function(){
    alert('hi');
    $(this).hide(); 
});

$('img').each(function() { this.src = this.src; });

jsFiddle here: http://jsfiddle.net/7cnQN/

+8

FF, IE, Chrome, Safari, Opera.

$('img').each(function() {
    var img = this;
    if (img.complete) {
        if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
            console.log(img, 'load failed');
        } else {
            console.log(img, 'load ok');
        }
    } else if (img.readyState == 'uninitialized') {
        console.log('load failed - IE');
    } else {
        $(img).error(function() { console.log(img, 'load failed - error()'); });
        $(img).ready(function() { console.log(img, 'load ok - onload()'); });
    }
});
+2

jQuery(document).ready() jQuery(window).onload() img , . :

jQuery('img').live('error',function(){
            alert('hi');
        jQuery(this).hide(); 
        });

jQuery (document).ready();

( ). , .

0

JQuery, , , , JavaScript. onerror, :

myimage.onerror = function() { this.style.visibility = 'hidden'; }

( )

0

.error() docs :

$("img").error(function(){
  $(this).hide();
});

... , . , jQuery ? , FireFox, Chrome Safari, javascript .

EDIT: :

, . HTTP, , , , URL- file:.

?

0

:

jQuery('img').each(function(i,img){
    jQuery('img').bind('load',function(){ this.show(); });
    if (img.complete)
        jQuery(img).show();
});

Bind the event first, then check if the image (.complete) is uploaded and show it. This will require that you hide all the images before you start using the script or inside the inline style of individual images. Using a well-known container as an area ...

jQuery('#container img')

... you can limit this behavior to a subset of images.

0
source

You are dealing with a race condition. jQuery may or may not load when loading an image. The following code handles both cases.

$('img').each(function() {
    var img = this;
    if (img.complete) {
        if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
            console.log(img, 'load failed');
        } else {
            console.log(img, 'load ok');
        }
    } else {
        $(img).error(function() { console.log(img, 'load failed - error()'); });
        $(img).ready(function() { console.log(img, 'load ok - onload()'); });
    }
});
0
source

All Articles