'IEs understanding of 'this'

In this code, Firefox sees 'this' as the element that was clicked and passes the href attribute through the right way.

IE seems to think that 'this' as [object window] instead. How would I get this to work the same way in both browsers?

Note: jQuery would be lovely, but is not an option for this project

var printElem = getElementsByClassName('print', 'a');
for(i in printElem){
    ObserveEvent(printElem[i], 'click', function(e){
        window.open(this.href, '', 'location=0,menubar=1,resizable=1,scrollbars=1,width='+810+',height='+700);
        cancelEvent(e);
    });
}


Solution 1:[1]

You can use the event target, like this:

    ObserveEvent(printElem[i], 'click', function(e){
            var target = e.target || e.srcElement;
            window.open(target.href, '', 'location=0,menubar=1,resizable=1,scrollbars=1,width='+810+',height='+700);
            cancelEvent(e);
    });

Solution 2:[2]

The problem almost certainly stems from the ObserveEvent function using IE's attachEvent method, which (unlike addEventListener in other browsers) doesn't set this to the object being observed in the event handler.

Solution 3:[3]

Another option: Create a closure to scope the element for the handler for each element:

var printElem = getElementsByClassName('print', 'a');
for(var i in printElem){
  (function(elem) { // elem === printElem[i] at time of execution later
    ObserveEvent(elem, 'click', function(e){
      window.open(elem.href, '', 'location=0,menubar=1,resizable=1,scrollbars=1,width='+810+',height='+700);
      cancelEvent(e);
    });
  })(printElem[i]); // immediately call the temp function with our element
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex Gyoshev
Solution 2 Tim Down
Solution 3 gnarf