How to handle broken image using jQuery

It is quite possible that sometimes the images on web page don't load properly. There can be many reasons for this problem like path of the image is changed or it is removed or renamed. So in such situation, the browser will display broken image sign. (Vary from browser to browser). To overcome this problem, we can use jQuery to handle such images. When the image is not loaded properly, one can use error method on images to handle such images. There are 3 possible solutions for this problem.

1. Hide the broken image.

$('img').error(function() {
  $(this).hide();
});

2. Remove the broken image

$('img').error(function() {
  $(this).remove();
});

3. Replace it with other image.

$('img').error(function() {
  $(this).src = "/images/noimage.gif";
  $(this).onerror = "";
}

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



Responsive Menu
Add more content here...