Fork me on GitHub


This script lets you intercept document-level keys, without completely breaking everything, allwhere, everywhen: it sets up intercepts for specific keys for specific elements, and only intercepts these keys when focus is on the indicated element. If focus is moved off of that element, key interceptions bound to that element are completely ignored.

This is very useful for things like browser games, or custom interaction elements, where something like "backspace" should, under no circumstances make the browser jump to the previous page. Similarly you can trap cursor keys, or the tab key, or what have you. And because the trapping is per element, your page won't break user interaction when the user is not focussed on your browser-behaviour-modifying element.


The API is simple. Include keytrap.js:

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

And then to add key trapping to elements, use KeyTrap.trap:

KeyTrap.trap(element, [<array of keycode numbers>], callback);

Or, if you loaded jQuery before loading keytrap.js, you can also use .trap() instead:

 $('selector').trap([<array of keycode numbers>], callback);

The first two arguments (for jQuery, just the first) are mandatory, the third is optional (for jQuery, the second). Keycodes are of the standard ASCII variety (backspace is 8, tab is 9, newline is 10, return is 13, cursor keys are left/top/right/down 37, 38, 39, and 40). The callback function gets called only when a key is blocked, with arguments (calling element, keycode).

download keytrap.js by clicking here.

As small demonstration, there is some vertical padding on this page to make the document handle up and down cursors. however, when focus is on any of the colored divs below, cursor keys never make it to the document. They are trapped.