6

I have the following image element that it's src does not exists. I want to use the jquery error function to detect if it has not loaded and replace the src with a generic image that I know exists. This works in chrome and firefox but on in IE. Why does this not work in IE and are there any workarounds? Thanks!

<img id="main" src="missing-image.jpg" />

<script type="text/javascript">

    $(function () {
        $("#main").error(function () {
            $("#main").attr("src", "generic.jpg");
        });
    });

</script>
Phil
  • 4,134
  • 4
  • 23
  • 40
  • 2
    take a look an similar question http://stackoverflow.com/questions/263359/how-can-i-determine-if-an-image-has-loaded-using-javascript-jquery – Carlos Cocom Jul 29 '11 at 14:11
  • It looks like jquery ignores .error() in IE if there is no file extension on the source. I had to use the workaround Carlos mentions in the comment above. – Buchannon Jun 11 '12 at 19:43

3 Answers3

3

Timing issue?

DEMO HERE

<img id="mainImage" src="placeholder.jpg" />

<script type="text/javascript">
$(document).ready(function() {
  $("#mainImage").error(function () {
    $(this).attr("src", "generic.jpg");
  });
  $("#mainImage").attr("src","possibly_missing_image.jpg");
});

</script>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • This still doesn't work in IE. I dont believe that "main" is a reserved word. – Phil Jul 29 '11 at 14:47
  • 1
    Note - This DOES NOT work in IE if your image source has no file extension. It looks like jquery ignores .error() in IE if there is no file extension on the source. I used something like this as a workaround: http://stackoverflow.com/questions/263359/how-can-i-determine-if-an-image-has-loaded-using-javascript-jquery – Buchannon Jun 11 '12 at 19:42
  • Something like this what? The deferred example [here](http://stackoverflow.com/a/9333069/295783) ? – mplungjan Jun 12 '12 at 05:45
3

I ran into the same problem with ie and setting the img src to itself allowed enough time for ie to catch the image error

$(document).ready(function() {
  $("#mainImage").error(function () { 
    $(this).attr("src", "generic.jpg");
  })
  .each(function() {
  $(this).attr("src",$(this).attr("src"));
  });
 });
Si8
  • 9,141
  • 22
  • 109
  • 221
pippit
  • 31
  • 1
0

Try this

$(function () {
        $("#main").bind('error abort', function () {
            $(this).attr("src", "generic.jpg");
        });
    });
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124