0

Can anyone see anything wrong with this? It stops the image changing when the image is not here as I want but it does not change the image all the time when it does!

Cheers, Shaun

var myFile = "/_images/multi/" + productCode + "/" + imgCodeAlt + "_l.jpg";
if (myFile.exists()) {
    $("#imgMain img").attr({
        rel: 'lightbox',
        src: "/_images/multi/" + productCode + "/" + imgCodeAlt + "_l.jpg"
    });
}
Esailija
  • 138,174
  • 23
  • 272
  • 326
Shaun Hogg
  • 177
  • 2
  • 14

4 Answers4

1

You can't check for files existing in Javascript due to it being a client side language.

You could try an ajax request to the file, and if it returns a 404 status code, the file does not exist - seems messy though.

royse41
  • 2,310
  • 4
  • 22
  • 29
1

I dont think there is a exists function in javascript which can check if a file exists on some location. If you really want to check existence of file the only way you can do it in js is using ajax. check this post How do I check if file exists in jQuery or JavaScript?

Community
  • 1
  • 1
sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
1

Your code will work if you define exists like this:

String.prototype.exists = function() {
    var a = new XMLHttpRequest;
    a.open( "GET", this+"", false );
    a.send( null );
    return a.status === 200;
};

"/".exists() //true
Esailija
  • 138,174
  • 23
  • 272
  • 326
0

What is exists() for? If you're trying to check if the file exists from JavaScript, then this isn't going to work using that method in JS.

I would suggest using an AJAX call if you need to verify the existence of a file.

Rhys
  • 1,439
  • 1
  • 11
  • 23