Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Check if image exists

Tags:

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?

like image 493
Marko Avatar asked Jul 25 '10 01:07

Marko


People also ask

How check file exist or not in jQuery?

Approach 1: Use ajax() method of jQuery to check if a file exists on a given URL or not. The ajax() method is used to trigger the asynchronous HTTP request. If the file exists, ajax() method will in turn call ajaxSuccess() method else it will call Error function.


1 Answers

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...

like image 162
Reigel Avatar answered Sep 27 '22 21:09

Reigel