Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

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

You are here: irt.org | FAQ | JavaScript | Image | Q981 [ previous next ]

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?'

©2018 Martin Webb