↓ I built a game! Check it out ↓

Use Your Own Custom Broken Image Icon For Your Website

December 4, 2018 by Andreas Wik

Are you sick of the standard broken image icons the web browsers out there use? Luckily, there’s a really simple way to replace it with your own custom image.

Did you know that the img element has an onerror attribute? Using this, we can easily manipulate the element’s src attribute. This way, whenever the image doesn’t load because of a faulty src attribute URL, we can replace the attribute with our own URL using a little JavaScript.

Here’s how:

<img src="https://awik.io/this-img-does-not-exist.jpg" onerror="this.src='https://awik.io/img-not-found-icon.jpg'">

 

Or, to just simply hide the image element completely, set its CSS display property to none:

<img src="https://awik.io/this-img-does-not-exist.jpg" onerror="this.style.display='none'">

 

Ofcourse we could do a lot more than just replacing the src. Maybe we’d want to show different broken image icons depending on the size of the element, or adda background color, a border, or whatever. If this is the case, then maybe you’d prefer to place all of this stuff inside of its own function and just call that:

<body> 

  <img src="https://awik.io/this-img-does-not-exist.jpg" onerror="this.src='handleBrokenImg(this);'">

  <script>

    function handleBrokenImg(el) {

      // Perhaps show different broken image icons depending on various conditions
      // Or add some style to it.. a border, background color, whatever..

      el.src='https://awik.io/wp-content/uploads/2018/12/broken-img.png';
    }

  </script>
  
</body>

 

A CodePen for you to play around with:

See the Pen Using your own custom broken image icon by Andreas Wik (@andreaswik) on CodePen.

Share