Tuesday, January 25, 2011

jQuery/Javascript to replace broken images

Many times you find your image links are broken. In firefox, Chrome if your images links are broken then your images are hidden by default. If you see same scenario in IE it will show you 'X' image missing.

I found following snippet quite useful which hides broken images using jquery.



$(document).ready(function(){ 
    $("img").each(function(index) {
        $(this).error(function() {
            $(this).unbind("error").attr("src", "/images/NoImage.png"); // If you want to replace with any blank image.

            $(this).hide();//You can simply Hide it using this.
        });
        $(this).attr("src", $(this).attr("src"));
  });    
});

Hope you find it useful.

5 comments: