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.
The keydown event is fired when a key is pressed. Unlike the deprecated keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.
keydown – fires when any key is pressed down, fires first, and always before the browser processes the key (e.g. inserting text, moving focus, etc). keypress – fires when a key that produces a character value is pressed down, fires after keydown , and before the browser processes the key.
The keydown event is sent to an element when the user presses a key on the keyboard. If the key is kept pressed, the event is sent every time the operating system repeats the key. It can be attached to any element, but the event is only sent to the element that has the focus.
The keypress ignores keys such as delete , arrows , page up , page down , home , end , ctrl , alt , shift , esc , etc. So, if we need to handle those keys, it's better to use either keydown or keyup event. }); The keydown and keypress events fire multiple times if user press and hold a key.
The simple solution: just use the keyup event (and not the keydown event). This will give you the latest value after the user typed the latest character. That resolves the issue.
The 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With