I am writing a userscript with the following code:
(function() {
'use strict';
window.addEventListener("keydown", arrows, false);
function arrows(e) {
debugger;
switch(e.keycode) {
case 37: alert("Left"); break;
case 39: alert("Right"); break;
}
}
})();
Eventually the left and right cases will navigate to the previous and next articles in a series, respectively, with something like:
window.location = String(parseInt(window.location.href.match(/\d+$/))-1);
However, pressing the arrow keys does not cause an alert. The script is clearly loaded, the Chrome developer menu shows the arrows()
function is registered as an event listener for window.keydown
, and yet the function never fires. I added debugger;
to the arrows()
function, but the debugger does not show when I press the arrow keys.
I am writing a userscript with the following code:
(function() {
'use strict';
window.addEventListener("keydown", arrows, false);
function arrows(e) {
debugger;
switch(e.keycode) {
case 37: alert("Left"); break;
case 39: alert("Right"); break;
}
}
})();
Eventually the left and right cases will navigate to the previous and next articles in a series, respectively, with something like:
window.location = String(parseInt(window.location.href.match(/\d+$/))-1);
However, pressing the arrow keys does not cause an alert. The script is clearly loaded, the Chrome developer menu shows the arrows()
function is registered as an event listener for window.keydown
, and yet the function never fires. I added debugger;
to the arrows()
function, but the debugger does not show when I press the arrow keys.
3 Answers
Reset to default 12The event propagation is probably getting stopped at some point on the handler for an element, before it bubbles up to window
(probably due to a poorly-written onkeydown
returning false
to prevent the default action, not caring that this also stops propagation).
You should attach your listener with capturing, so that it will capture the event at window
, before it bubbles:
// note the third parameter
window.addEventListener("keydown", arrows, true);
You have mispelled the keyCode:
switch(e.keyCode) { // Code is uppercase
case 37: alert("Left"); break;
case 39: alert("Right"); break;
}
Your events might be being caught as expected. Use console.log
instead of alert
to validate that event got caught. Reasons why it does not work with alert
are unknown for me: I suspect it has something to do with event fire timing and alert dialogs stopping normal workflow
keydown
event (in which case you should set the third parameter ofaddEventListener
totrue
to enable capturing)? – Stuart P. Bentley Commented Jun 6, 2016 at 16:00