Hide an image entirely when it does not load in HTML
Well, this one blew my mind completely when I got to know about it. So, you probably are aware of the fact that the
<img> tag is used for displaying images on websites.
Now, if the URL of the image that you give to the
src attribute of the
<img> tag is working fine, it will flawlessly render the image but the moment something goes wrong, let’s say the image URL is down for some reason, the browser will render a broken image icon to indicate that the image is not rendered.
But do you know, you can override this behavior with a single line?
The thing is,
you can set an
onerrorevent handler on the image that will trigger an event If an error occurs while loading or rendering an image.
So, you can use this to your advantage and hide the image completely if the browser is not able to render it like so.
<img src="https://www.amitmerchant.com/images/php8-in-a-nutshell-cove.jpg" onerror="this.style.display='none'" >
As you can tell, when the error occurs, an event will be triggered where you can write the logic to hide the image.
Generally, the best practice is to provide an
alt attribute to the image. So, when the image is not loaded, the browser will show the alt text.
But if the image that you want to load is non-essential and doesn’t have an alt text, it’s no brainer to hide it entirely!
Watch it in action.
I learned about this trick in one of the tweets by Juan David Meza.