3

Given an image url below http://www.bikewalls.com/pictures/abc.jpg (does not load)

I need a javascript/jquery function/code to alert saying the above url is valid or not.These urls will be passed as parameters. Taking the case of above example will be very helpful.

Mirza Vu
  • 1,532
  • 20
  • 30
  • 1
    And where did you get stuck writing this function? – David Thomas Feb 28 '14 at 23:42
  • 1
    In [this prior StackOverflow answer](http://stackoverflow.com/questions/9714525/javascript-image-url-verify/9714891#9714891) is a function called `testImage()` that takes an image URL to test and will call your callback and tell you if the image loaded successfully or not. – jfriend00 Feb 28 '14 at 23:50

2 Answers2

2

You can use the onload and onerror callback like this:

var img = new Image();
var url = "http://www.vbarter.com/images/content/3/2/32799.JPG";
img.onload = function(){
    alert("the image exists");
    // display image or whatever you need
};
img.onerror = function(){
    alert("error while loading..");  
    // handle the error
}

img.src = url;

FIDDLE: http://jsfiddle.net/473GV/

BeNdErR
  • 17,471
  • 21
  • 72
  • 103
0

Quick and simple using jQuery:

$("<img/>")
    .load(function() {
        console.log("image loaded correctly");
    })
    .error(function() {
        alert("error loading image");
    })
    .attr("src", $(originalImage).attr("src"));

Obviously you would have to adapt this to your particular case, but you get the idea. You can read more about jQuery's $.error() here.

Drewness
  • 5,004
  • 4
  • 32
  • 50