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

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.

Tags: jquery change missing image src, jquery missing image event
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

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!