JavaScript
Article
By Sam Deering

jQuery Bind Error Msg to Image

By Sam Deering
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

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).

--ADVERTISEMENT--

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.

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?