views:

307

answers:

2

How can I determine the image src of the image that triggered the event in the onload and onerror event handlers in IE? This example code I threw together:

<script language="javascript" type="text/javascript" src="jquery.js"></script>
<script language="javascript" type="text/javascript">
function loadImages() {
   var goodImage = new Image();
   var missingImage = new Image();

   $(goodImage).bind('load', function(event){
      $("#log").append( $(event.target).attr('src') + ' WAS FOUND <br>');
   });

   $(missingImage).bind('load', function(event){
      $("#log").append( $(event.target).attr('src') + ' WAS FOUND <br>' );
   });

   $(goodImage).bind('error', function(event){
      $("#log").append( $(event.target).attr('src') + ' IS MISSING <br>');
   });

   $(missingImage).bind('error', function(event){
      $("#log").append( $(event.target).attr('src') + ' IS MISSING <br>');
   });

  goodImage.src = 'GOOD-IMAGE.GIF'; // this image exists
  missingImage.src = 'MISSING-IMAGE.GIF'; // this image doesn't exist
}

</script>
</head>
<body onload="loadImages();">
<div id="log"></div>

works in FF but in IE8 it prints out undefined for the $(event.target).attr('src') part. I thought jQuery was supposed to normalize the event object for IE so that it acted like other browsers? I've tried a number of permutations but haven't been able to get anything to work in IE8.

Anyway if anyone has a suggestion on how to figure out the image src in the onload and onerror event handlers that works in IE I would really appreciate it. Or even how to figure out after the images have loaded which have loaded and which haven't (but not graphically - I need to generate an array containing the filenames of the images that didn't load). Thanks!

+1  A: 

In Firefox and all good browsers it's .target; in IE it's .srcElement. Just insert this line before each append:

var targetEl = event.target || event.srcElement;

Then change event.target to:

targetEl
Delan Azabani
Delan - nice try and thank you for the info. I tried that but IE8 uses event.target in this case (I believe because jQuery resets the event object for IE to act as much as possible like W3C compliant browsers) so this didn't solve my problem.
Bill
A: 

OK, I figured it out.

You have to use the currentTarget property of the event object not the target property - i.e.,

  $("#log").append( $(event.currentTarget).attr('src') + ' WAS FOUND <br>');

works both in FF and IE8.

Bill