Search code examples
javascriptjqueryhtmlonerror

Attaching event handler for onerror to an image does not work in IE


I am trying to attach an event handler for the onerror event to an img element so that it will replace it with some text if there is an error while loading it.

I can get it to work in Chrome and Firefox but it will not work in IE. I am using IE11.

This is my image element:

<img class="image-class" src="someURL" />

And the javascript:

<script type="text/javascript">
    $(document).ready(function () {
        var imageError = function (img) {
            $(img).after('<span>Replacement Text</span>');
            $(img).remove();
        };
        var handler = function (e) {
            imageError(e.currentTarget);
        };
        $('.image-class').each(function () {
            $(this).error(handler);
        });
    });
</script>

I have tried binding the event in the html itself with:

<img class="image-class" onerror="imageError(this)" src="someURL" />

I noticed when debugging in Chrome that after executing the $(this).error(handler) line, the img element still had onerror defined as null.

Does anyone know why this is not working in IE, and how I could get it to work in IE?


Solution

  • Here, give the following a try - it works just fine in IE 9. I suspect the problem has either to do with jQuery's expectations or the way you've used inline JS to apply the function to the image (possibly a combination of the 2).

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    function byId(e){return document.getElementById(e);}
    function newEl(tag){return document.createElement(tag);}
    
    window.addEventListener('load', onDocLoaded, false);
    
    function onImgError(evt)
    {
        console.log("onImgError fired");
        console.log("Img id: " + this.id);
    
        var parent = this.parentNode;
        var span = newEl('span');
        span.innerHTML = "broken image replacement text";
        parent.insertBefore(span, this);
        parent.removeChild(this);
    }
    
    function onDocLoaded()
    {
        var mImg = byId('mImg');
        mImg.addEventListener('error', onImgError, false);
        mImg.src = "imgs/girl.png";
    }
    </script>
    <style>
    </style>
    </head>
    <body>
        <img id='mImg' title='image error test'/>
    </body>
    </html>