How does one use the onerror attribute of an img element

HtmlCssImageOnerror

Html Problem Overview


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.

Html Solutions


Solution 1 - Html

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;.

Solution 2 - Html

This is actually tricky, especially if you plan on returning an image url for use cases where you need to concatenate strings with the onerror condition image URL, e.g. you might want to programatically set the url parameter in CSS.

The trick is that image loading is asynchronous by nature so the onerror doesn't happen sunchronously, i.e. if you call returnPhotoURL it immediately returns undefined bcs the asynchronous method of loading/handling the image load just began.

So, you really need to wrap your script in a Promise then call it like below. NOTE: my sample script does some other things but shows the general concept:

returnPhotoURL().then(function(value){
    doc.getElementById("account-section-image").style.backgroundImage = "url('" + value + "')";
}); 


function returnPhotoURL(){
    return new Promise(function(resolve, reject){
        var img = new Image();
        //if the user does not have a photoURL let's try and get one from gravatar
        if (!firebase.auth().currentUser.photoURL) {
            //first we have to see if user han an email
            if(firebase.auth().currentUser.email){
                //set sign-in-button background image to gravatar url
                img.addEventListener('load', function() {
                    resolve (getGravatar(firebase.auth().currentUser.email, 48));
                }, false);
                img.addEventListener('error', function() {
                    resolve ('//rack.pub/media/fallbackImage.png');
                }, false);            
                img.src = getGravatar(firebase.auth().currentUser.email, 48);
            } else {
                resolve ('//rack.pub/media/fallbackImage.png');
            }
        } else {
            img.addEventListener('load', function() {
                resolve (firebase.auth().currentUser.photoURL);
            }, false);
            img.addEventListener('error', function() {
                resolve ('https://rack.pub/media/fallbackImage.png');
            }, false);      
            img.src = firebase.auth().currentUser.photoURL;
        }
    });
}

Solution 3 - Html

very simple

  <img onload="loaded(this, 'success')" onerror="error(this, 
 'error')"  src="someurl"  alt="" />

 function loaded(_this, status){
   console.log(_this, status)
  // do your work in load
 }
 function error(_this, status){
  console.log(_this, status)
  // do your work in error
  }

Solution 4 - Html

> replace product.invoice_url to your dynamic url

<img onerror="this.onerror=null;this.src='https://upload.wikimedia.org/wikipedia/commons/1/14/No_Image_Available.jpg';" [src]="product.invoice_url" class="img-thump" >

css

  .img-thump{
    height: 120px;
    width: 170px;
  }

Solution 5 - Html

In ReactJS:

const Avatar = ({className, src, alt, ...props}) => {
const handleOnError = (e) => {
    e.target.src =
      "https://www.kindpng.com/picc/m/22-223863_no-avatar-png-circle-transparent-png.png";
}
return (
  <div>
    {src ? (
      <img
        {...props}
        className={`defaultClass ${className}`}
        src={src}
        alt={alt}
        onError={handleOnError}
      />
    ) : (
      <img
        {...props}
        className={`defaultClass ${className}`}
        src={
          "https://www.kindpng.com/picc/m/22-223863_no-avatar-png-circle-transparent-png.png"
        }
        alt={alt}
      />
    )}
  </div>
);}

In the above code, handleOnError function is triggered whenever it detects an invalid src link so we can assign the default link in this function.

If you want to see the implementation of the onError attribute in react you can check this video:

How to make a perfect Avatar Component

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShahrukhView Question on Stackoverflow
Solution 1 - HtmlŠime VidasView Answer on Stackoverflow
Solution 2 - HtmlRonnie RoystonView Answer on Stackoverflow
Solution 3 - HtmlMustkeem KView Answer on Stackoverflow
Solution 4 - HtmlShashwat GuptaView Answer on Stackoverflow
Solution 5 - HtmlAnkur KunalView Answer on Stackoverflow