DEV Community

Sham Gurav
Sham Gurav

Posted on

( HTML Tip ⚡ ) - Specify Fallback Image if Actual Image not found

Use onerror event When you need to specify a backup image in case if the actual image is not found or not available on the server for any reason.

<img src="image.gif" 
onerror="this.onerror = null ; this.src = 'imagenotfound.gif' ">

Enter fullscreen mode Exit fullscreen mode

Note - The reason we have the "this.onerror=null" in the function is that the browser will be stuck in an endless loop if the onerror image itself generates an error.

Resources -

  1. https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror

Top comments (0)