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

Q52 How do I check if an image file exists?

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

Netscape 3+ supports the image objects onError method:

<img src="http://www.anywhere.com/myimage.gif" height="100" width="100" onerror="alert('Image missing')">

Note: You need to use onerror, not onError otherwise it won't work in Internet Explorer.

Ryan Kelly writes:

You can also use the Image() object to test for the existence of a generic image (or any number of images) without ever displaying them on the page:

<script language="JavaScript"><!-
function testImage(URL) {
    var tester=new Image();
    tester.onLoad=isGood;
    tester.onError=isBad;
    tester.src=URL;
}

function isGood() {
    alert('That image exists!');
}

function isBad() {
    alert('That image does no exist!');
}
//--></script>

This can be useful if, for example, the user must specify an image and you want to check whether it exists before submitting the form.

©2018 Martin Webb