jQuery Bind Error Msg to Image

Sam Deering

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.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments

Comments on this post are closed.