Explain Codes LogoExplain Codes Logo

Jquery/javascript to replace broken images

javascript
image-handling
error-handling
cross-browser
Anton ShumikhinbyAnton Shumikhin·Aug 6, 2024
TLDR

Here's a quick jQuery snippet to tackle missing images. It hooks onto the error() event and immediately switches the src attribute to a default image using .attr():

$("img").on("error", function() { $(this).attr("src", "default.png"); });

The code above listens for load errors (polite speak for "Hey, this image you're trying is MIA"), then swaps the src with "default.png". It's like your site's image search-and-rescue team.

Picasso goes full4G: Handling Images that Never Loaded

When an artwork, sorry image, fails to make it, a graceful fallback is to dress 'em up with a nice, uniformly styled placeholder. How? Use the onerror attribute packed into the img tag. With onerror, the browser is told to raise a JavaScript fire drill when an image load goes haywire.

Pure JavaScript, the Jeff Bezos style

No jQuery? Want to rebel against the establishment? Say hello to pure JavaScript:

document.addEventListener("DOMContentLoaded", function() { var imgElements = document.getElementsByTagName('img'); for(var i = 0; i < imgElements.length; i++) { imgElements[i].onerror = function() { this.src = 'default.png'; // Fallback image. The "Lean on me" for images. this.onerror = null; // Putting a stop to a potentially infinite loop (no, not the infinity war!) }; } });

Look carefully. It's this!

The this keyword here is like your honing arrow. It points precisely to the image object in peril, and switching its source helps fix the situation like a magic wand. Virtual high-fives, anyone?

Nip that loop in the bud

You love watching Infinite War, but you won't enjoy a potential infinite loop when your fallback image is also AWOL. Thanks to the image.onerror = null; peace pact, your error handler relaxes once the replacement image checks in.

Your cross-browser tour guide

Different browsers are like your aunts and uncles at a family picnic: they deal with image loading issues each in their own precious way. Thus, testing across browsers is like making sure your beloved aunts and uncles are happy with the picnic arrangements. Trust me, the extra work pays off!

Old is not always gold: jQuery's error() method

If you're on jQuery 1.8, ditch the .error(handler) high school romance for the hot new flame .on('error', handler). One small change, one big step for your codebase!

Direct is beautiful: No event delegation, please

Remember those action movies where messages never reached the right ears? Turns out, image error events don't like Chinese whispers either: bind your error handler directly to those img elements.

The nerd zone: DOM-Level-2-Events and quirksmode.org

If you feel JavaScript is your spirit animal, consider exploring majestic lands such as DOM-Level-2-Events or quirksmode.org. Your one-way ticket to JavaScript nirvana.