Preface: All modern browsers support addEventListener
, even IE9+, with the caveat that IE9-IE11 will hobble themselves by default via (in)Compatibility Mode on intranet sets and (I think) in some other contexts. You can tell IE9-IE11 not to hobble themselves by sending the X-UA-Compatible
header from the server, or including it as a meta
tag at the beginning of head
. (This answer claims you actually have to send it from the server, but I believe it's incorrect; it's just that if you put the meta
tag further down, IE may ignore it.) So unless you need to support IE8, you probably don't need a cross-browser alternative anymore.
Neither of them does a thorough job of normalizing what the event handler deals with.
The differences you need to handle are:
The value of this
when calling the handler
Where the event
object comes from
The methods available on the event
object
The part you don't understand:
html_element.attachEvent("on" + event_name, function() { event_function.call(html_element); }); //<-- This I don't understand
...is trying to handle the first of those, the value of this
within the callback. Function#call
calls a function allowing you to set a specific value for this
to have during the call. So event_function.call(html_element)
calls event_function
with this
equal to html_element
.
Some time back, for this answer, I wrote this which does a fairly thorough job:
var hookEvent = (function() {
var div;
// The function we use on standard-compliant browsers
function standardHookEvent(element, eventName, handler) {
element.addEventListener(eventName, handler, false);
return element;
}
// The function we use on browsers with the previous Microsoft-specific mechanism
function oldIEHookEvent(element, eventName, handler) {
element.attachEvent("on" + eventName, function(e) {
e = e || window.event;
e.preventDefault = oldIEPreventDefault;
e.stopPropagation = oldIEStopPropagation;
handler.call(element, e);
});
return element;
}
// Polyfill for preventDefault on old IE
function oldIEPreventDefault() {
this.returnValue = false;
}
// Polyfill for stopPropagation on old IE
function oldIEStopPropagation() {
this.cancelBubble = true;
}
// Return the appropriate function; we don't rely on document.body
// here just in case someone wants to use this within the head
div = document.createElement('div');
if (div.addEventListener) {
div = undefined;
return standardHookEvent;
}
if (div.attachEvent) {
div = undefined;
return oldIEHookEvent;
}
throw "Neither modern event mechanism (addEventListener nor attachEvent) is supported by this browser.";
})();
Then you'd use it like this in your example:
hookEvent(document.getElementById("hd_vertical"), "click", function(e) {
// ...
});