SignalLeaf allows a podcaster to specify an image for the podcast and/or episodes. To do this, you paste a URL to an image in to an input box. It’s a pretty standard setup, over-all.
With this being a public facing system, letting people specify any URL they want often leads to mistakes – the most common of which is pasting in a web page URL that contains the image they want. For example, someone might paste a media file location from a WordPress blog, and accidentally paste the view page instead of just the image URL. When this happens, I want to show people a friendly error message to say something went wrong and they need to fix it. Fortunately, this is fairly simple with jQuery and the error / load methods for loading images.
Handling Errors On Image Load
The first thing to set up is a jQuery selector around your image tag, and for the “change” event of the input for the URL. Once you have that, can call the .error method on the img selector object. In this callback, run additional code to show an error message of some kind.
In my case, I’m showing a previously hidden error message and also hiding the image preview “img” tag. The end result looks like this:
(note that I left the single pixel border an image preview space in place, to show that no image was loaded)
Handling Successful Image Load
With the error handler in place, you will also need a success handler for when the image loads properly. You don’t want to continue showing the error message, or hiding the image when it does load successfully after all.
Modify the existing code to add a .load method call on to the img tag selector. This takes another callback which can be used to show the image preview and hide the error message.
The end result is what I showed in the first screenshot above – a successful image load with the URL in the input box.
A Note On When To Wire This Up
One thing you need to watch for, is when you wire up the .error and .load callback methods. You need to ensure this is done before the <img> has a src attribute – before the image is loaded. If you don’t put the error and load callbacks in place prior to the the image source being set, the callback methods won’t be fired and things won’t work.
A Much Better User Experience
Having a simple set up to show error messages like this is one way to help create a better user experience. Instead of just giving people an input box and hoping for the best, this code provides immediate feedback on whether or not they got it right. Giving your users that kind of knowledge, as quickly as possible, will save a lot of frustration and headache for the people using your system and for the support people who would have to help fix simple mistakes that could have been avoided.