Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q981 Is there any way to test the presence of an image before attempting to display the image?

irt.org | Knowledge Base | JavaScript | Image | Q981 [ previous next ]

Q981 Is there any way to test the presence of an image before attempting to display the image?

You can detect if the image request failed using the images onError event handler supported by browsers that support the Image object:

<img src="http:///www.somewhere.com/remoteimage.gif" onError="this.src='localimage.gif'">

You can even check for the image before displaying it so that it works the other way around:

<img src="localimage.gif" width="50" height="50">

<img src="http:///www.somewhere.com/remoteimage.gif" width="1" height="1" onLoad="document.images['otherImageName'].src=this.src">

It is also possible to do this without even displaying the image:

<script language="JavaScript"><!--
var myImage =new Image();
myImage.onerror = myError;
myImage.src = 'http:///www.somewhere.com/remoteimage.gif';

function myError() {
    myImage.src = 'localimage.gif';
}
//--></script>

Feedback on 'Q981 Is there any way to test the presence of an image before attempting to display the image?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.