26

Possible Duplicate:
Check if image exists with given url using jquery
Change image source if file exists

I am throwing the value of an image path from a textbox into boxvalue and want to validate if the image exist using javascript.

 var boxvalue = $('#UrlQueueBox').val();

I browsed stackoverflow and found the below to get the image width/height, but don't want to use this.

var img = document.getElementById('imageid'); 

How can an I validate if it is really an image from the image path?

Community
  • 1
  • 1
X10nD
  • 21,638
  • 45
  • 111
  • 152
  • 4
    Look this thread: http://stackoverflow.com/questions/5678899/change-image-source-if-file-exists – Felipe Oriani Feb 01 '13 at 17:03
  • @FelipeOriani That is to create a new image. – X10nD Feb 01 '13 at 17:04
  • What exactly is your question? I don't see any question marks in your post... – maerics Feb 01 '13 at 17:05
  • @maerics - How can an I validate if it is really an image from the image path? – X10nD Feb 01 '13 at 17:08
  • To those who hit the close of the question, please read the question again. I do not want to do it from #SelectorID but from the image path. The question highlighted as duplicate is using the #SelectorID. – X10nD Feb 01 '13 at 17:11
  • [You asked the same thing more than 2 years ago](http://stackoverflow.com/questions/3381663/check-if-image-exists-with-given-url-using-jquery). What do you want to know now? – vault Feb 01 '13 at 17:16
  • @vault Nice find. But if you see closely it is still the image #selectorid not the direct image check. – X10nD Feb 01 '13 at 18:05
  • Don't stop at first answer, [what about Helmut's one](http://stackoverflow.com/a/11775226/1521064)? – vault Feb 01 '13 at 18:13
  • @vault That is ajax which I do not want. maerics has already given the answer I require. – X10nD Feb 01 '13 at 18:21

2 Answers2

73

The general strategy is to use an DOM Image object instance, set the src property to the URL of the image you want to check (which will cause the browser to fetch and load the image), and then handle the load and error events to determine existence or absence, respectively.

Here's an example promise-based approach:

function imageExists(url) {
  return new Promise(resolve => {
    var img = new Image()
    img.addEventListener('load', () => resolve(true))
    img.addEventListener('error', () => resolve(false))
    img.src = url
  })
}

const url = 'http://www.google.com/images/srpr/nav_logo14.png'
imageExists(url)
  .then(ok => console.log(`RESULT: exists=${ok}`))
  //                    => RESULT: exists=true
maerics
  • 151,642
  • 46
  • 269
  • 291
  • 2
    This test creates a new image which is saved under Resources --> Images in the Google Chrome browser whether or not the url is a valid image or not which I don't particularly like. – Flying Emu Feb 12 '15 at 06:59
  • 2
    This is great, but can you get it to return the URL? I've got a loop that tries to load an icon for a list, and I need something that will return either the URL you tried, or a default URL if the image doesn't exist. All the solutions seem to run some code or dump to the console. – chazthetic Dec 31 '15 at 19:35
  • 1
    not an expert but this still helped end of 2019 (vue/nuxt) thanks... –  Sep 30 '19 at 17:38
  • Nice that onerror is not an attribute, follows https://stackoverflow.com/a/59366589/458321 - The attribute is deprecated, not the event. Doesn't work in IE11 (for those who have to provide commercial support) – TamusJRoyce Feb 18 '21 at 19:38
8

You can create a function and check the complete property.

function ImageExists(selector) {
    var imageFound = $(selector); 

    if (!imageFound.get(0).complete) {
        return false;
    }
    else if (imageFound.height() === 0) {
        return false;
    }

    return true;
}

and call this funciton

 var exists = ImageExists('#UrlQueueBox');

Same function with the url instead of a selector as parameter (your case):

function imageExists(url){

    var image = new Image();

    image.src = url;

    if (!image.complete) {
        return false;
    }
    else if (image.height === 0) {
        return false;
    }

    return true;
}
UrbiJr
  • 133
  • 1
  • 2
  • 20
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
  • 1
    Can it be done without the #selector or #Id. I want it directly from the path. – X10nD Feb 01 '13 at 17:07
  • will that work in all browser, because that will work, if the image that already loaded is cached. and so the creation of a new image, will just load the already cached one. But if that process failed, then it will fail, it's the case when the cache is disabled. Still a good function though. – Mohamed Allal Nov 21 '17 at 19:12