Use modern event handling. On any half-decent up-to-date browser that's
document.addEventListener("keydown", keydownScreenHandler_1, false);
document.addEventListener("keydown", keydownScreenHandler_2, false);
On IE8 and earlier, or IE9-IE11 in their broken "compatibility" mode, it's:
document.attachEvent("onkeydown", keydownScreenHandler_1);
document.attachEvent("onkeydown", keydownScreenHandler_2);
There are other differences between attachEvent
and addEventListener
, such as where you get the event object from. If you need to support obsolete browsers like IE8 (or IE9-IE11 in (in)compatibility mode), this answer has a function to handle almost all the differences for you.
Updated snippet using addEventListener
:
function keydownScreenHandler_1(event) {
alert('- 1 -');
}
//Register the keydown event handler:
document.addEventListener("keydown", keydownScreenHandler_1, false);
function keydownScreenHandler_2(event) {
alert('- 2 -');
}
//Register the keydown event handler:
document.addEventListener("keydown", keydownScreenHandler_2, false);
<h1>
Click here to get focus, then press a key
</h1>
Updated snippet using hookEvent
from the linked answer:
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.";
})();
function keydownScreenHandler_1(event) {
alert('- 1 -');
}
//Register the keydown event handler:
hookEvent(document, "keydown", keydownScreenHandler_1, false);
function keydownScreenHandler_2(event) {
alert('- 2 -');
}
//Register the keydown event handler:
hookEvent(document, "keydown", keydownScreenHandler_2, false);
<h1>
Click here to get focus, then press a key
</h1>