How does one use the onerror attribute of an img element

This works:

<img src="https://stackoverflow.com/questions/8124866/invalid_link"
     onerror="this.onerror=null;this.src="https://placeimg.com/200/300/animals";"
>

Live demo: http://jsfiddle.net/oLqfxjoz/

As Nikola pointed out in the comment below, in case the backup URL is invalid as well, some browsers will trigger the “error” event again which will result in an infinite loop. We can guard against this by simply nullifying the “error” handler via this.onerror=null;.

Leave a Comment