I have a web page that includes a bunch of images. Sometimes the image isn't available, so a broken image is displayed in the client's browser.
How do I use jQuery to get the set of images, filter it to broken images then replace the src?
--I thought it would be easier to do this with jQuery, but it turned out much easier to just use a pure JavaScript solution, that is, the one provided by Prestaul.
This is JavaScript, should be cross browser compatible, and delivers without the ugly markup
onerror=""
:CODEPEN:
Pure JS. My task was: if image 'bl-once.png' is empty -> insert the first one (that hasn't 404 status) image from array list (in current dir):
Maybe it needs to be improved, but:
So, it will insert correct 'needed.png' to my src or 'no-image.png' from current dir.
Handle the
onError
event for the image to reassign its source using JavaScript:Or without a JavaScript function:
The following compatibility table lists the browsers that support the error facility:
http://www.quirksmode.org/dom/events/error.html
Here is a standalone solution:
This is a crappy technique, but it's pretty much guaranteed:
Here is an example using the HTML5 Image object wrapped by JQuery. Call the load function for the primary image URL and if that load causes an error, replace the src attribute of the image with a backup URL.