Checking if image does exists using javascript [duplicate]

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?

Answers:

Answer
// The "callback" argument is called with either true or false
// depending on whether the image at "url" exists or not.
function imageExists(url, callback) {
  var img = new Image();
  img.onload = function() { callback(true); };
  img.onerror = function() { callback(false); };
  img.src = url;
}

// Sample usage
var imageUrl = 'http://www.google.com/images/srpr/nav_logo14.png';
imageExists(imageUrl, function(exists) {
  console.log('RESULT: url=' + imageUrl + ', exists=' + exists);
});
Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.