Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching img load error for <img> tags created after page load (e.g. via AJAX)

I'm using jQuery's error event handler to catch image loading errors. It looks like this:

$(function(){
  $('img').error(function(){
    // ... do something
  })
})

This works great for images that are in the DOM when the page is loaded. However, I'd like to catch the errors for <img> tags that get inserted via AJAX, too. I'd prefer to not have to run certain code after every AJAX call.

I'd like something like this, although this doesn't seem to work:

$('body').on('error', 'img', function(){
  // ... do something
})
like image 333
nicholaides Avatar asked Mar 15 '12 04:03

nicholaides


1 Answers

If you don't want to set the binding after every ajax call, you might want to set it in a global ajax complete function

//Gloabal Ajax Complete
$("body").bind("ajaxSend", function(e, xhr, settings){
   //Sent
}).bind("ajaxComplete", function(e, xhr, settings){
   //Complete
   $('img').error(function(){
       // ... do something
   })
}).bind("ajaxError", function(e, xhr, settings, thrownError){
    //Error
});
like image 106
Amin Eshaq Avatar answered Oct 27 '22 04:10

Amin Eshaq