2.11.2009

Attaching keyboard events to alternative browser objects

It took me way too long to find out why I could not listen to keyboard events for DOM objects other than the window, form objects, or links. All you have to do is give the div or any other DOM element a tabindex. Below is an example using the prototype framework.

  1. var myDiv = new Element('div' { 'tabindex': '0' })

  2. myDiv.observe('keypress', function(e) {

  3.   var code;

  4.   if (!e) var e = window.event;

  5.   if (e.keyCode) code = e.keyCode;

  6.   else if (e.which) code = e.which;

  7.   alert(String.fromCharCode(code));

  8. });

No comments:

Post a Comment