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.

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

No Reader comments

Comments on this post are closed.