15
$(function() {
    $("<img>", {
        src: "http://www.google.com.sg/intl/en_ALL/images/logos/images_logo_sm.gif",
        error: function() { alert("error!"); },
        load: function() { alert("ok"); }
    });
});

Got inspiration from How can I test if a URL is a valid image (in javascript)?

UPDATE

The next step will be: how can I encapsulate this logic into a function. I tried this -> http://jsfiddle.net/wp7Ed/2/

$(function() {
    function IsValidImageUrl(url) {
        $("<img>", {
            src: url,
            error: function() { return false; },
            load: function() { return true; }
        });
    }
    alert(IsValidImageUrl("http://www.google.com.sg/intl/en_ALL/images/logos/images_logo_sm.gif"));
    alert(IsValidImageUrl("http://error"));
});

but of course it fails... how can I return from an internl event handler? Or how can I implement this?

1

2 Answers 2

22

You cannot ever turn an asynchonous call into a synchronous one in javascript.

error and load are asynchronous events, so you have to do it like this:

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

IsValidImageUrl("http://www.google.com.sg/intl/en_ALL/images/logos/images_logo_sm.gif");
IsValidImageUrl("http://error");

or you can parse in callback function you define elsewhere like this:

function myCallback(url, answer) {
    alert(url + ': ' + answer);
}

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

IsValidImageUrl("http://www.google.com.sg/intl/en_ALL/images/logos/images_logo_sm.gif", myCallback);
IsValidImageUrl("http://error", myCallback);

The clean and performant version skips the jQuery overhead like this

function myCallback(url, answer) {
    alert(url + ': ' + answer);
}

function IsValidImageUrl(url, callback) {
    var img = new Image();
    img.onerror = function() { callback(url, false); }
    img.onload =  function() { callback(url, true); }
    img.src = url
}

IsValidImageUrl("http://www.google.com.sg/intl/en_ALL/images/logos/images_logo_sm.gif", myCallback);
IsValidImageUrl("http://error", myCallback);
Sign up to request clarification or add additional context in comments.

6 Comments

+1 for a great answer, but you need to add the callback argument to the IsValidImageUrl calls in the jQuery version.
Thx for noticing,. callbacks have been added
Thx, but if I need to validate a user input? How can I do that? I need to know if the form is valid b4 I submit. How would you do it? I will be using jQuery Validate, but for now a simple example will do
You could disable the submit button until the check is done. the check could then be done by hooking into the onchange event of the text field where the user types the image URL into (if thats the case) - it all depends on your solution, there are always many different ways to reach the same goal, usually the constraints are what code you already have and are unwilling to change.
I had found that it loads a large part of the file before checking if the url was indeed an image, for example a large mp4 would be almost completely downloaded before detecting it wasn't an image :/
|
0

I think yes because an error event is fired when image is not found. As in your code, if image is not found (meaning not a valid path to an image), the alert will come up with message error!.

Here is another version of how it might look:

$('#imgID').error(function(){
  alert('image not found !');
});

You can also change the path of your image in case previously specified image was not found like this:

$('#imgID').error(function(){
   this.src = 'new path to some image';
});

1 Comment

Thanks, I want to do something more realistic and encapsulate the logic into a function, how can I return from the handlers? jsfiddle.net/wp7Ed/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.