Thomas Ward
Thomas Ward

Reputation: 2752

UserScript to take actions based on Key Press?

I'm struggling with the syntax for this user script I'm trying to write, which should basically follow this logic:

IF (LeftArrowKeyIsPressed) THEN doSomething;
ELSE IF (RightArrowKeyIsPressed) THEN doSomethingElse;
ELSE IF (any other key pressed) THEN doNothing;

Can someone help me out with the code syntax for structuring the check for the keypress? Assume an onkeydown event is being used.

Upvotes: 3

Views: 2786

Answers (1)

Brock Adams
Brock Adams

Reputation: 93483

Add an event listener, probably to the window, using addEventListener. Then switch off the Event.which value to do what you want.

Here's the code. See it in action at jsFiddle.:

/*--- Get or set the codes for the arrow keys.
    Firefox gives us nice constants, Chrome does not.
*/
KeyEvent        = (typeof KeyEvent === "object")  ?  KeyEvent  :  [];
const LEFT_KEY  = KeyEvent.DOM_VK_LEFT   ||  37;
const RIGHT_KEY = KeyEvent.DOM_VK_RIGHT  ||  39;

window.addEventListener ("keydown", keyboardHandler, false);

function keyboardHandler (zEvent) {
    var bBlockDefaultAction = false;

    //--- Assume we want only the plain keys, not the modified versions.
    if (zEvent.altKey  ||  zEvent.ctrlKey  ||  zEvent.shiftKey) {
        //-- Do nothing (most user-friendly option, in most cases).
    }
    else {
        if (zEvent.which == LEFT_KEY) {
            //DO LEFT KEY ACTION HERE.
            bBlockDefaultAction = true;
        }
        else if (zEvent.which == RIGHT_KEY) {
            //DO RIGHT KEY ACTION HERE.
            bBlockDefaultAction = true;
        }
    }

    if (bBlockDefaultAction) {
        zEvent.preventDefault ();
        zEvent.stopPropagation ();
    }
}

This code works on userscripts-applicable browsers (not IE). The jQuery version is the same except change the addEventListener line to:

$(window).keydown (keyboardHandler);

Upvotes: 3

Related Questions