IMG Default Image

by Jason on June 28, 2008

Do you find it a hassle to manage external images? One day all your images show up just fine, and the next you see the infamous red x in it’s place, signifying that the image is no longer available. Frustrating!

With this quick fix, you can say goodbye to that problem. With a quick javascript event function, you can easily replace broken images with a default image of your choosing without any crazy server-side file existence checks.

The way to accomplish this is to reset the img tags src attribute on the OnError event. This event is fired when an image cannot be loaded for whatever reason. Perfect time to replace the image with the default image!

Example:

<img src=”http://www.somedomain.com/someimage.jpg” onerror=’this.src=”/images/default.gif”‘ />

With this one JavaScript event function, you no longer have to worry about whether images will show up, and best of all, viewers of your site won’t think you are a slacker 😉

9 comments

Or you could not be a bandwidth thief and get your own copies.

by Ryan on August 24, 2008 at 8:22 am. #

This article has nothing to do with advocating the linking of images from other people’s websites without their permission. A lot of companies own several domains and cross-link them. Also, for services such as flickr this is a good method to use as a backup in-case an image cannot be retrieved.

I’d appreciate more constructive comments instead of blatant assumptions. Thanks.

by admin on August 24, 2008 at 8:51 am. #

Really useful stuff . Just the other day my boss asked me if we could change the error image …. the one with the little x in the corner … for a web app we are building .
I told him NO 😛 .
Looks like I was wrong.
Good thing he doesn’t know any programming :D.

Thanks for the article.
Stumbled.

by Now on August 24, 2008 at 11:16 am. #

I have several domains and I frequently crosslink between them. So who would I be stealing bandwidth from? I found this useful.

by gms9810 on August 24, 2008 at 2:16 pm. #

I enjoyed this, too. Typically I’d set a css rule: {img {background:url(‘image.png’)}, but that has drawbacks. I could see using both just in case Javascript is disabled though.

by Travis on August 31, 2008 at 2:31 pm. #

Really helpful, Thanks.

by Michael Chevalier on February 22, 2010 at 3:05 pm. #

I shall now proceed to build a statue in your likeness 🙂
One simple line of code – Youre my hero ! <3
Thank You so much !

M.

by Mia on June 25, 2010 at 1:22 pm. #

thank you sooo much!!

by m on November 16, 2010 at 7:07 am. #

Hey…this really helpfull……:-)
thanx a ton… 🙂

by Tarun on December 4, 2011 at 2:40 am. #

Leave your comment

Required.

Required. Not published.

If you have one.