Introduction
This article will explain my framework for capturing key presses.
Background
I've recently had to develop a WYSIWYG editor in HTML and JavaScript. There were several actions which work a lot better and are more efficient when accessed on shortcut keys than through the editor's UI. I wanted a generic way of handling this, and therefore developed the following code.
Prerequisites
This framework builds upon other frameworks I have developed. The page that implements the code in this article must also implement the following frameworks:
Using the code
Most of my frameworks require document events to be configured a certain way. The key framework is no different. This framework ties into to the onkeydown
and onkeyup
events of the body
. The events need to be configured as such:
<script language="javascript" type="text/javascript">
var OnBaseKeyDown = new uiEvent();
var OnBaseKeyUp = new uiEvent();
</script>
<body onkeydown="OnBaseKeyDown.Fire(e?e:null);" onkeyup="OnBaseKeyUp.Fire(e?e:null);">
There are other events that get configured this way in the complete framework, but these will be covered in the articles they are relevant to.
The following is the JavaScript for the key framework. This needs to be added after the definition of the OnBaseKeyDown
and OnBaseKeyUp
events.
var KeyState = {
Ctrl: false,
Shift: false
}
var KeyEventManager = {
EventMappings: new Array(),
Add: function(mapping) { this.EventMappings.Add(mapping); },
KeyUpHandler: function(e) {
var key = e ? e.which : event.keyCode;
if (key == 17)
KeyState.Ctrl = false;
if (key == 16)
KeyState.Shift = false;
var sKey = String.fromCharCode(key);
for(var x = 0; x < KeyEventManager.EventMappings.length; x++) {
var em = KeyEventManager.EventMappings[x];
if(KeyState.Shift == em.Shift && KeyState.Ctrl ==
em.Ctrl && sKey.toLowerCase() == em.Key.toLowerCase())
em.OnPress.Fire();
}
},
KeyDownHandler: function(e) {
var key = e ? e.which : event.keyCode;
if (key == 17)
KeyState.Ctrl = true;
if (key == 16)
KeyState.Shift = true;
}
}
var KeyEventMapping = function(shift, ctrl, key) {
this.Shift = shift;
this.Ctrl = ctrl;
this.Key = key;
this.OnPress = new uiEvent();
}
OnBaseKeyDown.Register(KeyFrameworkDown);
OnBaseKeyUp.Register(KeyFrameworkUp);
In this framework, there is an object called KeyState
. It contains two properties: Ctrl
and Shift
, that can be used at any time to check the pressed state of the Ctrl and Shift buttons.
The second object is the KeyEventManager
. This ties into the key up and key down events of the page; it manages the Ctrl and Shift states and raises events for any registered key mappings.
There is also a class called KeyEventMapping
. This contains an event called OnPress
. This is the event for which you register your code for execution.
The following example shows how the shortcut key framework can be implemented:
var kem = new KeyEventMapping(false, true, 'g');
kem.OnPress.Register(function() { alert('test'); });
KeyEventManager.Add(kem);