12

I want to check if an image exists on the given URL using jquery. For example how do I check that an image exists on this url.

https://www.google.com/logos/2012/hertz-2011-hp.gif

but not on this url

 http://www.google.com
Mohit Jain
  • 43,139
  • 57
  • 169
  • 274
  • see [there](http://stackoverflow.com/questions/169625/regex-to-check-if-valid-url-that-ends-in-jpg-png-or-gif), [there](http://stackoverflow.com/questions/3381663/check-if-image-exists-with-given-url-using-jquery) and [there](http://stackoverflow.com/questions/4669111/is-this-a-valid-test-to-check-if-a-url-refers-to-an-image-in-js-jquery) it will be useful – komelgman Feb 22 '12 at 12:46
  • [Here](http://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-javascript) is what you may be looking for. – buster Feb 22 '12 at 12:46

1 Answers1

27
function IsValidImageUrl(url) {
$("<img>", {
    src: url,
    error: function() { alert(url + ': ' + false); },
    load: function() { alert(url + ': ' + true); }
});
}

IsValidImageUrl("https://www.google.com/logos/2012/hertz-2011-hp.gif");
IsValidImageUrl("http://google.com");
Pal Singh
  • 1,964
  • 1
  • 14
  • 29
  • Have you tested this? For some reason I am trying to use this code in chrome and every thing is coming back false – IcedDante Aug 07 '14 at 14:06
  • 1
    oh, what's happening is this load executes in a separate thread. I was trying to return true false from the error load methods which wouldn't work. – IcedDante Aug 07 '14 at 14:14