Wednesday, May 25, 2011

How to handle missing Images in HTML


ShareThis

Try this simple code. Handle OnError event of Image-

<img src="http://www.satya-weblog.com/image.png" height="100px" width="100px" onerror="this.src = '/image/item-no-image.png'" />

Or-

<img src="http://www.satya-weblog.com/image.png" height="100px" width="100px" onerror="handleMissingImg(this);" />

  1. function handleMissingImg(ele) 
  2.      ele.src = '/image/item-no-image.png'

Or, you can also use this-

  1. function IsImageOk(img) { 
  2.  // During the onload event, IE correctly identifies any images that 
  3.  // weren't downloaded as not complete. Others should too. Gecko-based 
  4.  // browsers act like NS4 in that they report this incorrectly. 
  5.     if (!img.complete) { 
  6.         return false
  7.     } 
  8.  
  9.  // However, they do have two very useful properties: naturalWidth and 
  10.  // naturalHeight. These give the true size of the image. If it failed 
  11.  // to load, either of these should be zero. 
  12.    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) { 
  13.        return false
  14.    } 
  15.     // No other way of checking: assume it's ok. 
  16.     return true
  17. }