tags:

views:

96

answers:

3

Hello,

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

+4  A: 

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 { //do rest of code }
Sarfraz
@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
Jean
@Jean: Please post your code in your question to see what you have or how you need this.
Sarfraz
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
Jean
question edited................
Jean
@Jean: See my updated answer please.
Sarfraz
@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
Jean
A: 

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');
});
sje397
question edited................
Jean
A: 

check this http://jqueryfordesigners.com/element-exists/

Space Cracker