kentcdodds
kentcdodds

Reputation: 29051

Keyboard combination shortcuts

"Keymaster is a simple micro-library for defining and dispatching keyboard shortcuts in web applications."

Is there a good way to do multi-key keyboard combinations. For example, in Gmail, pressing g followed closely by i will take you to your inbox. If it's not supported in keymasterjs then is there an eloquent way to do this (I will possibly fork keymaster and add this feature).

Keymaster has no dependencies. I would love to stay that way... Thanks!

Upvotes: 2

Views: 92

Answers (1)

bfavaretto
bfavaretto

Reputation: 71918

I don't know keymaster, but you can easily accomplish that with a timer (setTimeout) from within a keypress event handler. Instead of acting immediately on a key press, add the key to a buffer, and wait for a second key until the timeout expires.

In code, that would be something like this:

var keyBuffer = [],
    timer;

document.addEventListener('keypress', function(e) {
    // Add current key to buffer
    keyBuffer.push(e.which);

    // Cancel previous timer
    clearTimeout(timer);

    // Set new timer
    timer = setTimeout(function() {

        // Pass a *copy* of the buffer into another function
        reactOnKey(keyBuffer.slice(0));

        // Clear buffer
        keyBuffer.length = 0;
    }, 1000)
}, false);


function reactOnKey(buffer) {
   console.log(buffer);   
}

http://jsfiddle.net/pGdsR/

Upvotes: 2

Related Questions