JAVASCRIPT: onerror image magic


HTML has a little-known event handler for <img> and <body> tags. I’m going to focus on <img> tags and how you can use this to clean up some 404s.

First, just a quick note about this event handler. You won’t find it in any W3C spec because it just isn’t there. Why? I don’t know, but I do know that it’s supported by Firefox and Internet Explorer 6/7 - which is ~90% of the browser usage and possibly more (read: I need to fire up my Mac and test it). Apparently, this event handler has been around for a long time - see this brief e-mail exchange on the HTML users group.

Okay, let’s get started. Recently, I was working with some external data where I didn’t know whether I would have an image with each item the data or not. This is a simple problem that can be solved using server side code (since the data feed needed to be parsed into a database table anyway). However, I found that the links to some of the images returned 404 errors. I’m not a usability expert, but have broken images looks pretty bad, even if you use alt attributes. The onerror event handler is perfect for this situation. Here’s how it works:

You assign the attribute to the image tag with some sort of error handler:

1
<img src="badimage.jpg" onerror="fixImage(this);" />

Then, create your error handler function. You could replace the image with a “No image” image (like I did):

1
2
3
function fixImage(img) {
  img.src = 'noimage.gif';
}

Or you could just remove the image altogether:

1
2
3
function fixImage(img) {
  img.parentNode.removeChild(img);
}

If you want to read more about using onerror with <body> tags, MDC has some documentation.

Information and Links

Join the community by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts
JAVASCRIPT: Iterating through objects, the easy way
JAVASCRIPT: Internet Explorer’s attachEvent breaks ‘this’

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!