Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

want to hide image when image is not found at the src location?

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

I have written this code but non available images are not hiding and still showing cross sign. Can anybody point out what can be wrong. I am writing this under document.ready and i have tried it under window.onload as well.

like image 581
sushil bharwani Avatar asked Nov 30 '10 18:11

sushil bharwani


1 Answers

The problem seems to be that by the time you bind your error event, the image's onerror has already fired. You can fire it again by resetting the img.src after binding the event. The following worked on IE8, FF, and Chrome.

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

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

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

like image 137
James Kovacs Avatar answered Sep 29 '22 18:09

James Kovacs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!