Key Handler

This script extends an element with a few simple methods to handle keyboard inputs. A good example where this might be useful is in a webapp where one would like to have keyboard shortcuts defined.

Extending HTML elements

As you probably knows by IE4+ supports expando properties on HTML elements. This means that IE remembers all properties on an HTML element although it doesn't know what to do with them. For example one might add an attribute called overSrc to an image element that can then be used in a custom script. A much lesser known feature is the expando methods. With this you can add methods to any HTML element. I'll show you a small (stupid) example.

document.all.anElement.setBackgroundColor = function (color) {
   this.style.backgroundColor = color;
}

Now one can call document.all.anElement.setBackgroundColor("white") to change the background color. Although this can be done in many different (and easier ways) this method allows a higher level of abstraction. Notice that this is the name of the actual element.

Keyboard Extensions

The first thing that is done is to add an expando property that contains an associative array that keeps track of the added keyboard shortcuts.

element._keyObject = new Array();
element._keyObject["keydown"] = new Array();
element._keyObject["keyup"] = new Array();
element._keyObject["keypress"] = new Array();

Then there are some expando methods added to add and remove keyboard shortcuts. These are kept in the right array according to the event type they are assosciated to.

element.addKeyDown = function (keyCode, action) {
   element._keyObject["keydown"][keyCode] = action;
}
	
element.removeKeyDown = function (keyCode) {
   element._keyObject["keydown"][keyCode] = null;
}

Hooking up the events

For this we first need a function for handling the event. This is also pretty straight forward and it checks the type of event and what key was pressed. With this info it looks if there is any action assosciated to this event and keycode and if there is it just calls that action. After this is done it justs assigns the function the event handlers of the element.

function handleEvent() {
   var type = window.event.type;
   var code = window.event.keyCode;

   if (element._keyObject[type][code] != null) 
      element._keyObject[type][code]();
}

element.onkeypress = handleEvent;
element.onkeydown = handleEvent;
element.onkeyup = handleEvent;

Usage

First you need to include the javascript file.

<script type="text/javascript" src="keyhandler.js"></script>

Then you need to add all the expando properties and methods but to make it easy for you I've created a function that does all this for you. This should not be called before the element is available.

addKeyHandler(document.body);

Notice that not all elements support keyboard events. Once this is done you can start adding your keyboard shortcuts. I'll show you how this is done in the demo section below.

Demo

Basic

Adding a single keyboard shortcut is easy. To find out the keyCode value use this.

document.body.addKeyPress(32, function(){alert("You pressed Space");});

This will result in an alert when space is pressed. Keyboard associations can be changed during run time. Below are two buttons, one that adds a keydown handler for the a key and on that removes the same.

<button οnclick="document.body.addKeyDown(65, function(){alert('a pressed');})">Add handler for <b>a</b></button>
<button οnclick="document.body.removeKeyDown(65)">Remove handler for <b>a</b></button>

The enter key has been hooked up to increase a counter.

var counter = 0;
function increaseCounter() {
   window.status = "counter = " + counter++;
}

document.body.addKeyPress(13, increaseCounter);document.body.addKeyPress(13, increaseCounter);

Using multiple keys

I haven't built in any special handling of multiple keys but this can be achieved a few simple ways. The window.event object has three properties that indicates whether the alt, ctrl or the shift key was pressed and these are called altKey, ctrlKey and shiftKey. Below is a handler that gives an alert if the user presses CTRL + C.

document.body.addKeyDown(67, function() {if (window.event.ctrlKey) alert("CTRL + C");});

To catch two keys where none of them are alt, ctrl or shift you need some more handling. The idea here is to have a boolean variable that indicates whether a key is down and then if both are true do something.

var w, q;
document.body.addKeyDown(81, function() {q = true; if (q && w) window.status = "q and w is pressed";});
document.body.addKeyUp(81, function() {q = false; window.status = "";});

document.body.addKeyDown(87, function() {w = true; if (q && w) window.status = "q and w is pressed";});
document.body.addKeyUp(87, function() {w = false; window.status = "";});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值