Skip to content

Instantly share code, notes, and snippets.

@kosinix
Created January 6, 2014 07:58
Show Gist options
  • Select an option

  • Save kosinix/8279644 to your computer and use it in GitHub Desktop.

Select an option

Save kosinix/8279644 to your computer and use it in GitHub Desktop.
Keyboard Experiment - Detecting keys in javascript. Live demo: http://jsfiddle.net/rsyz5xn6/
<!doctype html>
<html lang="en">
<head>
<title>Keyboard Experiments</title>
<script type="text/javascript" src="keyboard.js"></script>
</head>
<body>
Press either left or right arrow keys
</body>
</html>
(function() {
var KEY_LEFT = 37,
KEY_RIGHT = 39;
window.document.onkeyup = function(e) {
e = e || window.event; // Use param e if it exists. use window.event otherwise (for <=IE8)
var key = null;
if (e.keyCode) {
key = e.keyCode;
}
if ( key == KEY_LEFT ) {
// go left
var body=document.getElementsByTagName("body")[0];
body.innerHTML='left arrow pressed <<<';
} else if ( key == KEY_RIGHT ) {
// go right
var body=document.getElementsByTagName("body")[0];
body.innerHTML='right arrow pressed >>>';
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment