Javascript Detect Broken Image

We have no way to know if an image is broken or not especially if we are just hot linking it from some other site. Javascript’s onerror function just does that. To add a no-image-file as replacement instead of the broken image icon (which would make your site look unprofessional), use this function below.

?View Code JAVASCRIPT
1
2
3
4
5
6
function onImgError(source) {
  source.src = "no-image-125px.gif";
  // disable onerror to prevent endless loop
  source.onerror = "";
  return true;
}

and call it using this <img src="test.gif" onerror="onImgError(this)"/>

tip from: http://www.tech-evangelist.com/2007/09/15/missing-image-fix/

Bookmark and Share

Found this post useful? Buy me a cup of coffee or help support the sponsors on the right.

Related Posts with Thumbnails

(4 votes, average: 5.00 out of 5)
 Loading ...

7 Responses to “Javascript Detect Broken Image”

Pages: [1] 2 » Show All

  1. 1
    analyzediz Says:

    Great tip!

    Worked like a charm. I updated the method to take in the desired replacement image URL.

    Thanks again.

  2. 2
    Satya Says:

    Great tip!

    Amazed at the smoothness

  3. 3
    tech Says:

    yer welcome ;) . whatever problems you have with javascript, you let me know.

  4. 4
    binarystarr Says:

    Thats excellent, such an elegant solution. Many thanks.

  5. 5
    tech Says:

    thanks ;)

Pages: [1] 2 » Show All

Leave a Reply