2

I am making a form with some inputs, etc... And one of them asks for a URL of a picture, and I want the browser to verify if the url or the pic given is active and working.

So I have an img element next to the url input, and when this input is blurred, the src attribute of that img changes with javascript automatically and is set to the url given. I want to determine if the image loaded properly, or it isn't working. I don't know if there is a function to do that without the img element, but please help.

Delimitry
  • 2,987
  • 4
  • 30
  • 39
Agusfn
  • 83
  • 2
  • 12

3 Answers3

2

You can use the onerror and onload events on the img DOM element. Just make sure to set the callbacks before you actually set the src property of the image. The following code can be used to check to see if a URL is a valid image URL. You can use similar code to check if an image has loaded into an existing img element (just select that element instead of creating a new one).

var checkImage = function (url) {

  var image = document.createElement('img');

  image.onerror = function () {
      // image has failed to load
      console.log('url is not valid');
  };

  image.onload = function () {
      // image has loaded successfully
      console.log('url is valid');
  };

  image.src = url;
};
Bill
  • 25,119
  • 8
  • 94
  • 125
0

Alternatively, you can do something like this:

$.ajax({
    url:'http://www.example.com/yourimage.jpg',
    type:'HEAD',
    error: function(){
            //do sth to handle error
           },
    success: function(){
            //do sth when load succeeded
           }
});

The above code should check errors, like 404, etc.

Also, you might want to take a look at this answer.

Community
  • 1
  • 1
woodykiddy
  • 6,074
  • 16
  • 59
  • 100
  • This doesn't ensure that the url points to a valid image though, just that it is a valid url. – Bill Oct 09 '12 at 01:57
0

Using jQuery: http://jsfiddle.net/0kwsetp1/1/

$("input").on("blur change", function () {
    var image = $("#the-image"),
        $this = $(this),
        string = $this.val();

    image[0].onerror = function () {
        alert("Image could not be loaded");
    };
    image.attr("src", string);
});

Thanks to Bill for guiding me to onerror.

Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239