jQuery code to handle broken (not found) images in webpage

In this post, find out jQuery code to handle broken link images or not found images on a webpage. This can happen when path of the image is changed or it is removed or renamed. But this can be answered easily with jQuery. When the image is not loaded properly, use jQuery error event on images to handle HTTP errors.

The error event is sent to elements, such as images, that are referenced by a document and loaded by the browser. It is called if the element was not loaded correctly. Code is self explanatory and it is based on jQuery 1.7.2 version.

$(document).ready(function() {
   var backup_Img = 'images/noimage.gif';
   $("img").on('error', function(){
   $(this).prop('src', backup_Img);
   });
});

Note:

The event handler must be attached before the browser fires the error event, which is why the example sets the src attribute after attaching the handler. Also, the error event may not be correctly fired when the page is served locally; error relies on HTTP status codes and will generally not be triggered if the URL uses the file: protocol.

So error event may not work if you are testing it using file:// protocol. Instead, host it on web server and access using HTTP protocol.

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...