Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Check whether image exists

Status
Not open for further replies.

RevsEd

Programmer
Apr 2, 2001
33
GB
Hi,

I'm having a bit of a problem which is now driving me mad. Basically, I want to know whether the path to an image is correct... and if not display a "not found" image. It should be simple but... all the code I've seen on the net uses the onerror event - yet it fires regardless of whether the images exists or not.

Here's my test code:

Code:
testImage("path/folder/testimageurl.gif");

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!');}

If you run it you'll see that both the events fire - or at least they do on my machine (IE6). If you put a nonsense URL in... they still fire! Can anyone help, all I need is a way to be sure that an image exists or not. If there's a better way (one with a different event I can capture) that'd be great.

Thanks in advance


Darren Jones
 
This works:

Code:
<img src="path/folder/testimageurl.gif" onload="isGood()" onerror="isBad()">

Additionally, you are never actually loading your image in that JavaScript, but, rather, preloading. For what it's worth, when you're setting the function of an event handler, you don't use parentheses.

Code:
function testImage(URL) {
    var tester=new Image();
    tester.onLoad=isGood;
    tester.onError=isBad;
    tester.src=URL;
}

*cLFlaVA
----------------------------
Lois: "Peter, you're drunk!"
Peter: "I'm not drunk, I'm just exhausted from stayin' up all night drinking!
 
Hi cLFlaVA

thanks for the additional information. I don't really want to load the image at this point... I'm trying to work out the context I've come from, if the image isn't where I expect it I can back out a level ("../") and find it there.

I really don't want to use an actual <IMG> tag if I can help it... though maybe that with a style to "not" show the image if found will suffice?

I'd also really like to know whether the events fire correctly on my example. Every example on the net seems to think they do?!

Thanks again

Darren.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top