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:

  1. Thank you, this was extremely helpful.

    ReplyDelete
  2. Thank you man, It works on IE!

    ReplyDelete
  3. That really worked.

    ReplyDelete
  4. where do you put this in your document?

    ReplyDelete
    Replies
    1. You can put this under your html head tag.

      Delete