Search code examples
javascriptiframethisattachevent

Javascript alternative for this (IE)


I have something like the following code:

for(var i=0;i<4;i++) {
  frm = document.createElement("iframe");
  frm.width = "100";
  frm.height = "100";
  frm.src = "source.php";
  frm.id = "something";

  frm.attachEvent("load", function() { alert(this.id); //Here I need alternative for this.id });

  var frameDiv = document.getElementById("frameDiv");
  frameDiv.appendChild(frm);
}

It's simplified, but basicly it creates four iframes inside some div and I need to fire some actions based on the id of each frame, when it's completely loaded. It works well, but the problem is in IE. IE doesn't know operator this, so I can't access to the id of frame inside. Is there any alternative which I can use for IE?

Thanks for any help!


Abhijit: Actually, the whole code is like this:

if(frm.addEventListener) {
  frm.addEventListener("load", function() { alert(this.id); },false);
}
  else if(frm.attachEvent) {
  frm.attachEvent("onload", function() { alert(this.id); });
}
  else {
  frm.onload=function() { alert(this.id); };
}

So it should works in all browsers.


Solution

  • I'm not sure why this wouldn't work in IE, but changing

    frm.attachEvent("load", function() { alert(this.id); });
    

    to

    // wrap in an anonymous function to fix scope issues
    (function(frm) {
        frm.attachEvent("load", function() { alert(frm.id); });
    })(frm);
    

    should give you a consistent reference to the iframe.

    (Edit: Updated above code to fix scope issues within the loop. This is exactly why you should generally avoid creating closures in a loop like this - all frm references will point to the last defined iframe unless you take explicit measures to fix the scope.)