bebraw
12/10/2010 - 6:17 AM

keyboard.js

// basic API
shortcut.add(<hotkey>, <handler>, <options>);

// example
shortcut.add('a', function() {
        // do something cool now
        console.log('a was pressed!');
    },
    {
        // don't trigger on input. see other opts too
        disable_in_input: true
    }
);
$(document).on('mousemove', function() {
    if(keyboard.isPressed('a')) {
        // do something cool now
        console.log('The user pressed a while moving the mouse');
    }
})
var keyboard = function(window) {
    var keyboard = window.keyboard || {};

    if (!('isPressed' in keyboard)) {
        keyboard._keys = {};

        var handler = function(e, flag) {
            var key = String.fromCharCode(e.which).toLowerCase();

            keyboard._keys[key] = flag;
        }

        $(document).on('keypress', handler, true).
            on('keyup', handler, false);

        keyboard.isPressed = function(key) {
            key = key.toLowerCase();

            if(key in keyboard._keys) {
                return keyboard._keys[key];
            }

            return false;
        }
    }

    return keyboard;
}(window);