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?

9
  • 4
    Look this thread: stackoverflow.com/questions/5678899/… Commented Feb 1, 2013 at 17:03
  • @FelipeOriani That is to create a new image. Commented Feb 1, 2013 at 17:04
  • What exactly is your question? I don't see any question marks in your post... Commented Feb 1, 2013 at 17:05
  • @maerics - How can an I validate if it is really an image from the image path? Commented Feb 1, 2013 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. Commented Feb 1, 2013 at 17:11

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
not an expert 😊 but this still helped end of 2019 (vue/nuxt) thanks...
Nice that onerror is not an attribute, follows 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)
9

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;
}

2 Comments

Can it be done without the #selector or #Id. I want it directly from the path.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.