82

I want to check if an image exists using jquery.

For example how do I check this image exists

http://www.google.com/images/srpr/nav_logo14.png 

the check must give me a 200 or status ok

--------------edited-------------------

var imgsrc = $(this).attr('src');
var imgcheck = imgsrc.width;


if (imgcheck==0) {
alert("You have a zero size image");
} else { //do rest of code }

Thanks Jean

Huangism
  • 16,278
  • 7
  • 48
  • 74
X10nD
  • 21,638
  • 45
  • 111
  • 152

7 Answers7

80

Use the error handler like this:

$('#image_id').error(function() {
  alert('Image does not exist !!');
});

If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:

Update:

I think using:

$.ajax({url:'somefile.dat',type:'HEAD',error:do_something});

would be enough to check for a 404.

More Readings:

Update 2:

Your code should be like this:

$(this).error(function() {
  alert('Image does not exist !!');
});

No need for these lines and that won't check if the remote file exists anyway:

var imgcheck = imgsrc.width;    

if (imgcheck==0) {
  alert("You have a zero size image");
} else { 
  //execute the rest of code here 
}
jotamon
  • 1,532
  • 5
  • 18
  • 38
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • @sAc I dont have an id for the images, just want to check if file is present, else move on to execute the remaining code – X10nD Aug 01 '10 at 10:45
  • @Jean: Please post your code in your question to see what you have or how you need this. – Sarfraz Aug 01 '10 at 10:48
  • If you take a look at this url http://www.google.com/images/srpr/nav_logo14.png , if the image is present, it must give me the size, or a status 200/ok – X10nD Aug 01 '10 at 10:53
  • @sAc the imgsrc.width does not seem to be working. I am using the image url to obtain the width...The image url is being passed, checked by alert – X10nD Aug 02 '10 at 06:34
  • 1
    In most cases you will want to add async:false to the AJAX call, otherwise it will return at some random interval and can cause erratic results in your scripting. – Lance Cleveland Oct 13 '12 at 02:00
  • It works! However, I ran into a No Access-Control-Allow-Origin problem when using the method, anyone have a solution? – iplus26 Dec 17 '15 at 02:05
34
$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function(){
            //do something depressing
    },
    success: function(){
            //do something cheerful :)
    }
});

from: http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06

Sibeesh Venu
  • 18,755
  • 12
  • 103
  • 140
Helmut
  • 1,377
  • 1
  • 15
  • 25
  • 15
    WARNING: You'll get error: [XMLHttpRequest cannot load http://not.on.your.domain.com/someimg.jpg. No 'Access-Control-Allow-Origin' header is present on the requested resource.] So this is only a good choice if the image is on your server. – Twelve24 Oct 02 '14 at 00:10
14

if it doesnt exist load default image or handle error

$('img[id$=imgurl]').load(imgurl, function(response, status, xhr) {
    if (status == "error") 
        $(this).attr('src', 'images/DEFAULT.JPG');
    else
        $(this).attr('src', imgurl);
    });
Alper
  • 1,085
  • 3
  • 20
  • 39
kiev
  • 2,040
  • 9
  • 32
  • 54
5

Use Case

$('#myImg').safeUrl({wanted:"http://example/nature.png",rm:"/myproject/images/anonym.png"});

API :

$.fn.safeUrl=function(args){
  var that=this;
  if($(that).attr('data-safeurl') && $(that).attr('data-safeurl') === 'found'){
        return that;
  }else{
       $.ajax({
    url:args.wanted,
    type:'HEAD',
    error:
        function(){
            $(that).attr('src',args.rm)
        },
    success:
        function(){
             $(that).attr('src',args.wanted)
             $(that).attr('data-safeurl','found');
        }
      });
   }


 return that;
};

Note : rm means here risk managment .


Another Use Case :

$('#myImg').safeUrl({wanted:"http://example/1.png",rm:"http://example/2.png"})
.safeUrl({wanted:"http://example/2.png",rm:"http://example/3.png"});
  • 'http://example/1.png' : if not exist 'http://example/2.png'

  • 'http://example/2.png' : if not exist 'http://example/3.png'

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
4

From here:

// when the DOM is ready
$(function () {
  var img = new Image();
  // wrap our new image in jQuery, then:
  $(img)
    // once the image has loaded, execute this code
    .load(function () {
      // set the image hidden by default    
      $(this).hide();
      // with the holding div #loader, apply:
      $('#loader')
        // remove the loading class (so no background spinner), 
        .removeClass('loading')
        // then insert our image
        .append(this);
      // fade our image in to create a nice effect
      $(this).fadeIn();
    })
    // if there was an error loading the image, react accordingly
    .error(function () {
      // notify the user that the image could not be loaded
    })
    // *finally*, set the src attribute of the new image to our image
    .attr('src', 'images/headshot.jpg');
});
Community
  • 1
  • 1
sje397
  • 41,293
  • 8
  • 87
  • 103
2

jQuery 3.0 removed .error. Correct syntax is now

$(this).on('error', function(){
    console.log('Image does not exist: ' + this.id); 
});
bjornte
  • 749
  • 1
  • 9
  • 31
0

To handle the lazy loading with image existence check I followed this in jQuery-

$('[data-src]').each(function() {
  var $image_place_holder_element = $(this);
  var image_url = $(this).data('src');
  $("<div class='hidden-classe' />").load(image_url, function(response, status, xhr) {
    if (!(status == "error")) {
      $image_place_holder_element.removeClass('image-placeholder');
      $image_place_holder_element.attr('src', image_url);
    }
  }).remove();
});

Reason: if I am using $image_place_holder_element.load() method it will be adding the response to the element, so random div and removing it appeared me a good solution. Hope it works for someone trying to implement lazy loading along with url check.

Vishal Kumar Sahu
  • 1,232
  • 3
  • 15
  • 27