Skip to content

Instantly share code, notes, and snippets.

@ehgoodenough
Last active December 17, 2015 13:49
Show Gist options
  • Save ehgoodenough/5620109 to your computer and use it in GitHub Desktop.
Save ehgoodenough/5620109 to your computer and use it in GitHub Desktop.
As discussed over at www.stackoverflow.com/questions/14893988, binding the functionality of a keystroke to an action instead of a state will establish noninterrupting events while still preserving individual keystrokes.
var kbdin =
{
downbinded: new Object(),
upbinded: new Object(),
stroked: new Object(),
downbindKeystroke: function(keyCode, functionality)
{
this.downbinded[keyCode] = functionality;
},
upbindKeystroke: function(keyCode, functionality)
{
this.upbinded[keyCode] = functionality;
},
isDownbinded: function(keyCode)
{
return this.downbinded[keyCode];
},
isUpbinded: function(keyCode)
{
return this.upbinded[keyCode];
},
isStroked: function(keyCode)
{
return this.stroked[keyCode];
},
onDownstroke: function(event)
{
var keyCode = event.keyCode;
if(!this.isStroked(keyCode))
{
this.stroked[keyCode] = 1;
if(this.isDownbinded(keyCode))
{
this.downbinded[keyCode]();
}
}
if(this.isDownbinded(keyCode))
{
event.preventDefault();
}
},
onUpstroke: function(event)
{
var keyCode = event.keyCode;
delete this.stroked[keyCode];
if(this.isUpbinded(keyCode))
{
this.upbinded[keyCode]();
event.preventDefault();
}
},
handleKeystrokes: function()
{
for(var keyCode in this.downbinded)
{
if(this.isStroked(keyCode) > this.keyDelay)
{
this.downbinded[keyCode]();
}
}
for(var keyCode in this.stroked)
{
this.stroked[keyCode]++;
}
},
keyDelay: 5,
keyFrequency: 50
}
window.addEventListener("keydown", function(event) {kbdin.onDownstroke(event);}, false);
window.addEventListener("keyup", function(event) {kbdin.onUpstroke(event);}, false);
window.setInterval(function() {kbdin.handleKeystrokes();}, kbdin.keyFrequency);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment