Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple way to keep track of which keys are pressed at any one time.
var PressedKeys = function($elt) {
var pressed = {};
($elt || $(document)).on('keydown keyup', function(evt) {
pressed[evt.keyCode] = (evt.type == 'keydown');
});
return pressed;
};
// example
var pressedKeys = PressedKeys($('canvas.game'));
(function loop() {
if (pressedKeys['39']) {
// do something right
} else if (pressedKeys['37'] {
// do something left
}
window.setTimeout(loop, 80);
})();
@hrldcpr

This comment has been minimized.

Copy link

@hrldcpr hrldcpr commented Apr 11, 2012

why not just:
pressed[evt.keyCode] = (evt.type == 'keydown');

@hrldcpr

This comment has been minimized.

Copy link

@hrldcpr hrldcpr commented Apr 11, 2012

why not gist.

@mrcoles

This comment has been minimized.

Copy link
Owner Author

@mrcoles mrcoles commented Apr 11, 2012

done.

“gist do it!”

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment