Simple jQuery code snippet to bind an error message to an image so that if an image is not loaded then another image will replace it (such as a missing or default image).

HTML Code

<img alt="Book" id="book" />


The event handler can be bound to the image:

jQuery Code

jQuery(document).ready(function($) {
$('#book')
  .error(function() {
    alert('Handler for .error() called.')
  })
  .attr("src", "missing.png");
});

If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed: .error() event will not trigger when the src attribute is empty.

Sam Deering Sam Deering
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

No Reader comments

Stay ahead of the game Exclusive content for developers and digital experts Go Premium