Remove Broken Images Using Dojo

By  on  

In an effort to get better with the Dojo Toolkit, I've decided to port yet another one of my previous posts: Remove Broken Images Using MooTools or jQuery. Broken images are an eyesore to any website so there's no point to keeping them in the page. Here's how you can remove them on the client side.

The Dojo JavaScript

dojo.ready(function() {
	dojo.query('img').forEach(function(img){
		dojo.connect(img,'onerror',function() {
			dojo.destroy(img);
		});
	});
});

Just as simple as jQuery and MooTools -- just a different syntax!

Recent Features

  • By
    Regular Expressions for the Rest of Us

    Sooner or later you'll run across a regular expression. With their cryptic syntax, confusing documentation and massive learning curve, most developers settle for copying and pasting them from StackOverflow and hoping they work. But what if you could decode regular expressions and harness their power? In...

  • By
    Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event...

Incredible Demos

Discussion

  1. Some streamlining of your methods:

    dojo.query('img').connect('onerror', function() { dojo.destroy(this); });
    

    Nice site by the way :) Keep up the Dojo posts :)

  2. @Karl Tiedt: Applied to a collection — very nice! I’ll keep that in mind from this point forward.

  3. Robert Labbe

    Would you happen to have code to do this with prototype?

  4. Ben

    I wish images would fire an event if they didn’t load then we could put something in it’s place instead of going through every image checking. Kind of slow…

  5. @Ben: They do — they fire an onError event.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!