Adam Hutchinson's blog

Web stuff

Getting Key Names From Javascript Key Events

When using javascript key events to add keyboard shortcuts to sites, you often end up with a big mess of unreadable code. To find out which key has been pressed, you have to check against a keycode integer. There are plans to upgrade this with DOM Level 3’s new TextInput interface, but this has not been implemented yet in major browsers.

In the meantime, it would be nice to have a way to get the current key name without much hassle.

I was playing around with Firebug trying to find an easy way of doing this and came across the native KeyboardEvent object. This is an object used by the browser to describe keyboard events. It contains a few attributes related to these events, but more importantly (for our cause), it contains a list of constants mapping names to keys. Along the lines of:

1
2
3
4
5
{
  DOM_VK_ESCAPE: 27,
  DOM_VK_SPACE: 32,
  // and so on...
}

Jackpot!

It’s a simple case of swapping the keys and values of the constants into a new object and we can now look up key names from their respective keycodes.

1
2
3
4
5
6
7
  // Loop through the KeyboardEvent object and populate keyMap object
  for( var keyName in KeyboardEvent ){
    var keyCode = KeyboardEvent[keyName];

    keyName = keyName.replace('DOM_VK_','');
    this.keyMap[keyCode] = keyName;
  }

The code snippet above is taken from a javascript keyboard listener I made which allows you to specify functions to run when certain key combos are pressed.

If you’re interested, check it out on github!

jPresentation: A Javascript Banner Rotator

At my last job, my employer tasked me to rebuild, in javascript, the flash banner rotator we were using on a variety of sites. It was quite a complex system allowing transitiions between multiple slides, as well as effects within each slide… just to be awkward!

Here is the flash banner rotator we were using.

Up until I started work on this, I had only ever used Prototype. Being a bit wrong in the head, I decided that this would be the project that I used to learn jQuery. Somehow, I managed to create a jQuery plugin that actually did the job it was supposed to and replaced all our banners with it. Since then, it’s been sitting around in a github repo feeling all lonely, so it’s about time I at least mentioned it!

The code can be found here: jPresentation.

BEWARE: It’s very rough around the edges (as you would expect for my first foray into jQuery) but take a look and use it if you need to!