Capturing KeyPresses in Client Side Javascript in an XPage

It’s a silly little one this, but it’s caught me a couple of times.

When you’re writing client side Javascript in an XPage for a field or a button (for example) when the Javascript is rendered out to the browser it’s actually stored in a function which Dojo then links to the specific event being worked with after the page loads. What wasn’t obvious to me and took a few minutes to work out was if you want to catch a specific event like a key press, how do you get hold of the event object? I’m not going to go into the joys of how different browsers implement event handling, you can read more about it here.

Once you look at the source HTML that the XPage generates the solution is blindingly obvious, the object that you want to refer to is called “theEvent”. So if you want to do something when the return key was pressed, for example, then you may have something like this:

In the onkeypress event of the field you’d add:

if (getKeyPressed(thisEvent) == 13)
  doSomething();

And in a separate script library there’ll be the following code:

var nn=(document.layers)?true:false;
var ie=(document.all)?true:false;
function getKeyPressed(e) {
  var evt = window.event? event : e;
  var iKey = (evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
  return iKey;
}

Share