Capturing img errors for <img> tags created after page load (e.g. via AJAX)
I use jQuery 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 loads. However, I would like to catch errors for the <img>
tags, which will also be inserted via AJAX. I would prefer not to run certain code after every AJAX call.
I would like something like this, although this does not seem to work:
$('body').on('error', 'img', function(){ // ... do something })
If you do not want to establish a binding after each ajax call, you can set it in the 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 });
You can use the jQuery live () or delegate () or on () methods, depending on the version of jQuery you are using, to register an error event on the current and future image elements that you add to the document. See http://api.jquery.com/live/