1

If I'm working on a site and receive HTML content from another source and that source contains images it will show a "broken image" image.

Is there a way for me to define the broken image for the entire page using HTML or CSS and as an absolute last resort JavaScript function. A HTML or CSS option is preferred?

For example, let's sat your job was to replace every broken image with a picture of a rose. Would love CSS or HTML solution.

img {
  width: 100px;
  height: 100px;
}

img:invalid {
  border: 5px solid #ff0000;
}

img:error {
  border: 5px solid #ff0000;
}

div {
  background-color: lightblue;
  width: 100px;
  height: 100px;
  position: absolute;
  top: 100px;
  left: 100px;
}
<div>Here is some content next to an image that does not exist  <img id="image" src="nothing.jpg"> 
</div>

Here's what it looks like:

enter image description here

There are new CSS error selectors like invalid and error. Would it be a good idea to consider a pseudo-selector to match broken images?

This question wants to request answers related to those solutions.

Related but not CSS preferred:
Inputting a default image in case the src attribute of an html <img> is not valid?

1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231
  • Question updated to include CSS invalid and error pseudo selectors that. Please reopen. – 1.21 gigawatts Sep 27 '20 at 00:11
  • If all the images were opaque, you could simply set a background-image via CSS, but maybe it's even better fixing the links no? To do so, simply append a element pointing to the original source's location. – Kaiido Sep 27 '20 at 04:38

1 Answers1

1

I'm doubtful this is possible outside of JS.

Add an error event listener to the image. On error, reassign the src attribute to your 404 image. For example, using your HTML and your avatar as the 404 image:

for (const image of document.querySelectorAll('img')) {
  image.addEventListener('error', () => {
    image.src = 'https://www.gravatar.com/avatar/e3aa08907388338521f3d9cec7a13d32?s=32&d=identicon&r=PG';
  });
}
#image {
  width: 100px;
  height: 100px;
}

div {
  background-color: lightblue;
  width: 100px;
  height: 100px;
  position: absolute;
  top: 100px;
  left: 100px;
}
<div>Here is some content next to an image that does not exist  <img id="image" src="nothing.jpg"> 
</div>

If you happen to control the server all the images are hosted on, you could also add a handler in case no matching path is found for a requested image, and return the placeholder 404 image instead.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • If I run that loop after the document is loaded, "DOMContentLoaded" would it still trigger the error events? – 1.21 gigawatts Sep 26 '20 at 23:59
  • 1
    `document.querySelectorAll('img')` only selects elements currently in the document. If you need dynamic images too, either use event delegation or attach a listener when the image gets inserted. – CertainPerformance Sep 27 '20 at 00:08