jQuery: Check if image exists
Asked Answered
C

6

23

I'm loading an image path via jQuery $.ajax and before showing the image I'd like to check if it in fact exists. Can I use the image load/ready event or something similar to determine that the file path is valid?

Having .myimage set to display: none, I'm hoping to do something like

$(".myimage").attr("src", imagePath);
$(".myimage").load(function() {
    $(this).show();
});

Is anything like that possible?

Chuff answered 25/7, 2010 at 1:35 Comment(1)
This might help ambitionlab.com/…Mika
C
34

Well, you can bind .error() handler...

Update: In jQuery 3.0 and later:

$(".myimage").on("error", function() {
    $(this).hide();
});

note: .error() was deprecated in jQuery 1.8 and removed in 3.0 but in in older versions you can:

$(".myimage").error(function(){
  $(this).hide();
});

well, yours is okay already with load-event

$(".myimage").load(function() {
    $(this).show();
});

the problem with this is if Javascript was disabled the image will not ever show...

Classicize answered 25/7, 2010 at 1:45 Comment(3)
Oh really? I didn't think the load method could be used, I just posted it as an example of what I'm trying to do. Also I'm not concerned about Javascript being disabled since I'm using $.ajax to start with.. :) +1Chuff
please explain why the down-vote. So that this answer could be improved if you have something...Classicize
This seems to work only intermittently in Internet Explorer 9. (I haven't tested the other ie versions). I am using multiple $(document).ready functions but it seems to work without a hitch in the other browsers and no errors are being thrown. You can see it here - if a cover doesn't exist on the server, it means that it has been removed and then show the cover removed information. fordummiescovers.com/share.php?id=100 JS functionality: fordummiescovers.com/js/covercheck.jsMongoloid
A
22

Try:

function urlExists(testUrl) {
 var http = jQuery.ajax({
    type:"HEAD",
    url: testUrl,
    async: false
  })
  return http.status;
      // this will return 200 on success, and 0 or negative value on error
}

then use

if(urlExists('urlToImgOrAnything') == 200) {
    // success
}
else {
    // error
}
Aluminate answered 21/2, 2012 at 11:58 Comment(1)
This results in the following warning: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience."Selfexpression
G
7

An old thread I know but I think it could be improved. I noticed OP having intermittent problems which could be due to loading of the image and error checking simultaneously. It would be better to let the image load first and then check for errors:

$(".myimage").attr("src", imagePath).error(function() {
    // do something
});
Gestate answered 22/11, 2011 at 21:7 Comment(0)
O
4

Since you're already doing an AJAX request, I would offload this to the server-side app that is supporting your AJAX. It's trivial to check to see if a file exists from the server, and you could set variables in the data you send back to specify results.

Outermost answered 25/7, 2010 at 1:39 Comment(5)
-1 the .load() the OP is using is not an ajax.... api.jquery.com/load-eventClassicize
That's a decent answer and a possible alternative, but my question is if I can check with jQuery specifically.. +1 for the server method though.Chuff
I was so judging,.. +1... but then I will not take my -1 for you could just check it on client-side....Classicize
@Reigel: OP specifically mentioned that he was using AJAX to get his data in the first place, when describing his process. Further, any method to check if the file exists is going to have to send another request to the server anyway - you're either doing it server-side once, or you're doing extra client-side work to only to still have interactions with the server as a result of anything you do.Outermost
To clarify the above, you're never just checking for files on the client-side. Any code to do so will send at least one, and possibly many additional requests to the server. So it's far better to send the info back in the original interaction with the server.Outermost
J
2

This question is a couple years old, but here's a better example usage for the error handler for anyone looking at this.

$("img")
  .error(function(){
    $(this).hide();
  })
  .attr("src", "image.png");

You need to attach the error handler before you try to load the image in order to catch the event.

Source: http://api.jquery.com/error/

Jolenejolenta answered 13/6, 2013 at 4:34 Comment(0)
F
0

This is what I did of mine:

$.get( 'url/image', function(res){ 
    //Sometimes has a redirect to not found url
    //Or just detect first the content result and get the a keyword for 'indexof'
    if ( res.indexOf( 'DOCTYPE' ) !== -1 )  {
        //not exists
    } else {
        //exists
    }
});
Forseti answered 1/7, 2013 at 22:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.