3

Using jquery I need to invoke a function when an image is missing. I need to use jquery as I am match all images that contain a certain path. doing this in jquery is simpler.

I found an example online but cannot establish why it isn't working. Any help would be appreciated.

// tried this and didn't work
$(document).on('error', 'img[src*="/image/path/"]', function() {
  alert('error loading image ' + $(this).attr('src'));
});

// to rule out path condition i tried this and it also didn't work
$('body').on('error', 'img', function() {
  alert('error loading image ' + $(this).attr('src'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<img src="/my/image/path/foo/bar.jpg" />

Demo fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
steve
  • 471
  • 6
  • 15

2 Answers2

4

The cause of your issue is because the error event does not bubble, hence the delegated event handler you're attempting to use will not pick up the event from the document.

To fix this you'll need to use a static event handler defined directly on the img elements:

$('img[src*="/image/path/"]').on('error', function() {
  console.log('error loading image ' + $(this).attr('src'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<img src="/my/image/path/foo/bar.jpg" />

If you have any img elements which are dynamically appended to the DOM after the page loads you will need to manually bind this event handler to them at the point they are created.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

This should work, based on your fiddle:

$('img[src*="/image/path/"]').on('error', function() {
  alert('error loading image ' + $(this).attr('src'));
});
John McCollum
  • 5,162
  • 4
  • 34
  • 50