Griffin Young
Griffin Young

Reputation: 243

Javascript: keydown event not firing

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.

Upvotes: 8

Views: 14556

Answers (3)

user435421
user435421

Reputation: 927

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

Upvotes: 0

Stuart P. Bentley
Stuart P. Bentley

Reputation: 10675

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);

Upvotes: 12

Azamantes
Azamantes

Reputation: 1451

You have mispelled the keyCode:

switch(e.keyCode) { // Code is uppercase
    case 37: alert("Left"); break;
    case 39: alert("Right"); break;
}

Upvotes: 1

Related Questions