Acquiring Multiple Key Presses in JavaScript

While trying to emulate the wonderful “Speed Dial” feature available in the Opera Web Browser in a web-based project, I was looking to write JavaScript to capture multiple keystrokes before a certain action is executed. For eg. a screen of website links with their screenshot-thumbnails are displayed to the user, each website having it’s own numeric shortcut key. When the user pressed the appropriate key/key-combination, the respective site would open in a new tab.

The way to capture multiple events in JavaScript is pretty straightforward. We take advantage of the users being human! We capture keystrokes, using onkeyup/onkeydown/onkeypress, and append each keystroke to a variable (as a String). We then start a timer that counts down approx. 500 milliseconds, a fairly less time for the user to press another (or more) keys. Once the interval that was set times out, we make use of the data stored in the string, and once that’s done, we reset the variable’s value to an empty string.

The code and the demo below, show how JavaScript/jQuery can be used to capture multiple digits pressed by the user within a short duration of time (less than 400 milliseconds)

<script type="text/javascript">
var keys='';
function resetKeys(){
 alert(keys);
 keys='';
 timerHandle=null;
}
var timerHandle=null;
jQuery(document).ready(function(){
 $('body').keyup(function(e){
 var key = e.keyCode - 48;
 if(key > 0 && key < 10){
 keys += key.toString();
 if(!timerHandle){
 timerHandle=window.setTimeout("resetKeys()", 400);
 }
 }
 });
});
</script>

View Demo