bebraw
12/9/2010 - 3:54 PM

Keyboard wrapper for JS. Written for RightJS but ought to be easy to adapt to your framework.

Keyboard wrapper for JS. Written for RightJS but ought to be easy to adapt to your framework.

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