Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one use the onerror attribute of an img element

CSS:

.posting-logo-div { } .posting-logo-img {   height: 120px;   width: 120px; } .posting-photo-div {   height: 5px;   width: 5px;   position: relative;   top: -140px;   left: 648px; } .posting-photo-img {   height: 240px;   width: 240px; } 

HTML:

<div id="image" class="posting-logo-div">   <img     src="../images/some-logo1.jpg"     onerror="this.src='../images/no-logo-120.jpg';"     class="posting-logo-img"   /> </div> <div id="photo" class="posting-photo-div">   <img     src="../images/some-logo2.jpg"     onerror="this.src='../images/no-logo-240.jpg';"     class="posting-photo-img"   /> </div> 

This doesn't seem to work in Chrome or Mozilla but does work in IE.

like image 251
Shahrukh Avatar asked Nov 14 '11 16:11

Shahrukh


People also ask

What is Onerror in IMG tag?

Definition and Usage The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image). Tip: When used on audio/video media, related events that occurs when there is some kind of disturbance to the media loading process, are: onabort.

How do you use Onerror?

To use the onerror event, you must create a function to handle the errors. Then you call the function with the onerror event handler. The event handler is called with three arguments: msg (error message), url (the url of the page that caused the error) and line (the line where the error occurred).

What is Onerror attribute?

The onerror attribute fires when an error occurs while loading an external file (e.g. a document or an image).

What are the three information provided by Onerror () method?

The Error object and error. It contains 3 standardized properties: message, fileName, and lineNumber.


1 Answers

This works:

<img src="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;.

like image 138
Šime Vidas Avatar answered Sep 28 '22 03:09

Šime Vidas