javascriptjqueryhtmlbroken-image

jQuery/JavaScript to replace broken images


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.


Solution

  • Handle the onError event for the image to reassign its source using JavaScript:

    function imgError(image) {
        image.onerror = "";
        image.src = "/images/noimage.gif";
        return true;
    }
    
    <img src="image.png" onerror="imgError(this);"/>
    

    Or without a JavaScript function:

    <img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />
    

    The following compatibility table lists the browsers that support the error facility:

    http://www.quirksmode.org/dom/events/error.html