Well, I don’t know if there’s any way to solve this just through CSS, but what I usually do is use the event onerror
to capture when there is a failure when opening the image.
thus:
document.querySelector('img').addEventListener('error', function() {
// sua lógica aqui.
})
It is common to define another src
for the image, but you could also add a class to the image, or replace it with another element.
Example:
document.querySelector('.error').addEventListener('error', function () {
var div = document.createElement('div');
div.classList.add('img-error');
div.innerText = 'Imagem falhou';
this.replaceWith(div)
})
.img-error{
background-color: #ccc;
width: 100px;
height: 100px;
display: inline-flex;
justify-contents: center;
align-items: center;
}
<img src="https://i.stack.imgur.com/CF2nj.jpg?s=48&g=1">
<img src="nao_existe" class="error">
Observing: If you choose to exchange the src
of the image in onerror
, make sure the fallback image used to "cover the error" actually exists, otherwise it will cause an infinite loop in the call onerror
(already happened to me when I forgot to publish an image that represented the user without a photo).
Option 2
Another thing I like to do is wear background-image
in a div
with predefined formatting (a background-color
for example). Thus, when the image fails to load, the background-color
will be there to make the fallback.
Does this solution not solve? https://bitsofco.de/styling-broken-images/
– Ricardo Pontual
It’s well out there @Ricardopunctual if you want to create an example ai as a response to get registered on the site more consistently!
– hugocsl
@hugocsl good initiative +1. I gave an answer. I think the way is the same JS.
– Wallace Maxters
Attribute
alt
. If the image does not appear (if it has the wrong address or the images are disabled) or if the user uses a screen reader,alt="deu ruim"
– user60252
@Wallacemaxters even liked there, but has how to do with CSS tb I believe! Not that one option is better than the other...
– hugocsl
@Exact leocaracciolo is just that, but wanted to treat this standard behavior to leave a message better formatted for the user
– hugocsl
@hugocsl wrote a reply with the content of the link, with a basic explanation of how it works, for reference if the link is no longer available tomorrow :)
– Ricardo Pontual