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

Q52 How do I check if an image file exists?

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

Q52 How do I check if an image file exists?

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.

Feedback on 'Q52 How do I check if an image file exists?'


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.