JavaScript key binder

A simple script which allows to bind keys (or sequence of keys) to actions in javascript.

// initialize the binde
Bind.init();

// the function to bind
function aux () {
  alert('42 !');
}

// let's bind it to 't'
Bind.bind('t', aux);

// let's bind an anonymous function
Bind.bind('a', function () { alert('a')});

// binding some modifiers
Bind.bind('ctrl-a', aux);
Bind.bind('alt-a', auxi;
Bind.bind('shift-a', aux);
Bind.bind('ctrl-shift-a', aux);

// binding sequences
Bind.bind('alt-a return', aux);
Bind.bind('tab tab', aux);

That was the basic environment. The following is a little more advanced:

// limit to a single element of the page
Bind.init('id_de_mon_element');

Some pages require different states (or modes), it's possible to bind a key to a function if the page is in a particular state:

var state='state0';
Bind.init(window, 'state');

// bind t when state is state0
Bind.bind('t', function () {
  alert ('t in 0');
}, 'state0');

// bind t when state is state1
Bind.bind('t', function () {
  alert ('t in 1');
}, 'state1');

// change the current state
Bind.bind('s', function () {
  state = state == 'state0' ? 'state1' : 'state0';
});

Of course, you can also bind the following keys : tab, return, up, down, left, right, delete, backspace, escape, space. By the way, it is not case sensitive, so alt-t and AlT-T are equivalent.

The code is right below, and requires Prototype.

Downloaded : 180 times
File : bind.js
Size: 3 ko

Leave a Reply