BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News KeyboardJS 0.4.1 released

KeyboardJS 0.4.1 released

This item in japanese

KeyboardJS, a library written to make working with the keyboard in JavaScript a lot easier, last month saw its 0.4.1 release, which includes a number of bug fixes and new features. The KeyboardJS library aims to help front-end developers working with keyboard actions, e.g. introducing keyboard shortcuts in a website or a game. Without a library, you would have to use something like the following code to detect when both the J and K keys are pressed:

var jPressed = false,
	kPressed = false;

document.addEventListener('keydown', function (e) {
	if (e.keyCode === 74) {
		jPressed = true;
	} else if (e.keyCode === 75) {
		kPressed = true;
	}
	
	if (jPressed && kPressed) {
		// Both keys are pressed; log to console
		console.log('Both J and K are pressed');
	}
});

document.addEventListener('keyup', function (e) {
	if (e.keyCode === 74) {
		jPressed = false;
	} else if (e.keyCode === 75) {
		kPressed = false;
	}
});

Using KeyboardJS, you would need only the following somewhat more readable code:

KeyboardJS.on('j + k', function () {
	console.log('Both J and K are pressed');
});

It also allows the developer to specify the order the keys are pressed in (using the > operator), and, as well as the "and" demonstrated above, "or" using whitespace or a comma.

KeyboardJS made its 0.4.1 release last month, which, as 0.4.0 was not released, is a complete rewrite; in addition to fixing a number of bugs, it also includes a number of API changes. Two such changes are the addition of a KeyboardJS.getActiveKeys() function, which returns an array of currently pressed keys by name (this is what the KeyboardJS website on GitHub uses to output the names), and a number of the combination functions used to work with keyboard combinations have been moved to the KeyboardJS.combo object.

You can add KeyboardJS to your application by downloading it from GitHub (scroll to the "Get it Here" section) and adding the following HTML to your page before you need to use KeyboardJS:

<script src="keyboard.js"></script>

If you're still using XHTML, you'll need to add type="text/javascript" to the script tag.

Also you can load it as an AMD module via RequireJS.

A locale refers to the different keyboard layouts (for example, shift + 6 on a US keyboard is a caret character (^), while on German keyboards it is an ampersand (&). The library has to be told each locale to support. Currently KeyboardJS only supports US keyboard layouts, but it is fairly easy to add your own locales to the library - make sure to send a pull request back to the library if you add your own locale.

Rate this Article

Adoption
Style

BT