Explain Codes LogoExplain Codes Logo

Inputting a default image in case the src attribute of an html `` is not valid?

html
responsive-design
best-practices
web-development
Alex KataevbyAlex Kataev·Feb 23, 2025
TLDR

Whenever an <img> tag's src is unattainable, opt for onerror to designate a backup URL:

<img src="broken.jpg" onerror="this.src='default.png';" alt="description" />

In essence, this code endeavors to fetch broken.jpg, but counter-swings to default.png upon collision with an error. Rely on onerror for fluid transitions, reinforcing the user-centricity of your project.

Leveraging the HTML Object Tag

For a more thorough HTML-centric approach, utilize the <object> tag alongside fallback <img>:

<object data="image.jpg" type="image/jpeg"> <img src="default.png" alt="description" /> </object>

This formula exhibits default.png when image.jpg proves elusive. The <object> tag is broadly supported, delivering assured implementation on an array of browsers.

Entertainment Guaranteed: Enjoy While You Can

What if we treat error handling as an easter egg hunt?

<!-- Is this the Easter Bunny's correct address? --> <object data="easterbunny.jpg" type="image/jpeg"> <!-- Oops! He moved. But he left some eggs behind! --> <img src="eastereggs.png" alt="description" /> </object>

CSS Magic: Now You See Me, Now You Don't

Envision a default image overlay using the :before and content properties in CSS:

.img-container:before { content: url('default.png'); display: none; } .img-container img { display: block; } .img-container img:invalid + :before { display: block; /* It's like a magician's trick: Poof! A wild image appears! */ }

Embed images within the .img-container. Now your CSS tactic furnishes a preventative visual buffer, even before the actual content arrives.

Moving Beyond: Advanced Stuff using <picture>

For adaptive solutions, couple <picture> tags with <source> elements.

<picture> <source srcset="hero-image.webp" type="image/webp" /> <source srcset="hero-image.jpg" type="image/jpeg" /> <img src="default.png" alt="Hero Image" /> </picture>

With this setup, browsers recruit an ideal source, yet pivot to the <img> tag when need be.

Be Like Water: Responsive Adaptation

Exploit the media attribute to notch up responsive design. Ensure only the apt images load for various screen sizes.

<picture> <source media="(min-width: 800px)" srcset="large.jpg" /> <source media="(max-width: 799px)" srcset="small.jpg" /> <img src="default.png" alt="description" /> </picture>

Acts of Kindness: Alt Text

Adopt concise yet descriptive alt text for greater accessibility. This amplifies UX, specifically for text-centric browsers or visually impaired users.

<img src="broken.jpg" onerror="this.src='default.png';" alt="Kind words sometimes echo the longest." />

I've Got Your onerror Right Here

For a JavaScript-free solution, station onerror within the <img> tag itself:

<img src="image.jpg" onerror="if(this.src != 'default.png') this.src='default.png';" alt="description" />

To avoid a Groundhog Day scenario, ensure your onerror script includes a conditional to block repetitive triggers.

Pre-emptive Checks and Compatibility

Before you parachute into any fallback method deployment, assess browser support for the <object> tag on websites like Can I Use.

Color within the (CSS) Lines

For different scenarios, use CSS classes to define default images:

.img-error { background: url('default.png') no-repeat center center; display: inline-block; /* or block, i.e., whatever suits your needs */ }

Then, when life gives you broken images, you make lemonade:

<img src="broken.jpg" class="img-error" alt="description" />

Strap in for jQuery

If jQuery is your tool of choice, dynamically replace defunct images with crisp scripting:

$('img').on('error', function() { if (this.src !== 'default.png') { this.src = 'default.png'; } });

While depending on jQuery may not be ideal, it offers a flexible and nimble avenue for image error handling.

Let CSS Flex Its Muscles

Bypass heavy scripting and make your project leaner using CSS for error handling:

.img-error:after { content: ''; background-image: url('default.png'); /* additional styling to fit the container */ }

If JavaScript seems cumbersome, CSS can step in as a low-footprint rescuer.

onerror to the Rescue

The onerror attribute can effortlessly mutate the <img> tag's src to a default upon a loading mishap:

<img src="image.jpg" onerror="this.onerror=null;this.src='default.png';" alt="description" />

By inserting an additional onerror incapacitation, you can curb multiple fetch attempts of a faltering resource.

References