Best way to capture all key events for a web application? Best way to capture all key events for a web application? javascript javascript

Best way to capture all key events for a web application?


If you are making a sophisticated web-app with customized keyboard controls, the first thing you should do is alert the user that you are making a sophisticated web-app with customized keyboard controls. After that, tell them what the controls are and what they do.

Binding the keypress and keydown listeners to the document is the correct way to do it, but you have to remember to preventDefault and/or stopPropogation for keypresses that you want to override. Even if there is no default behavior, you will need to prevent them from cascading in case the user has rebound their default keyboard shortcuts.

Also, you will only be able to receive keyboard input when the page has focus.

When you say Delete I assume you mean the Backspace key as Delete generally referrs to the key next to Insert, Home, End, Page Up and Page Down.

Edit to add:

Be very careful about which keys you choose to override. If you're making an app to be used by people other than yourself, you have to worry about usability and accessibility. Overriding the Tab, Space and Enter keys is risky, especially for people using screen-readers. Make sure to test the site blind and fix any issues that may arise with traversing the page via the keyboard.


maybe you can use html-attribute ACCESSKEY and react onfocus. i.e.:

<input type="text" size="40" value="somefield" accesskey="F">

i think u might need to add a tabindex to tags like <div>

<div id="foo" tabindex="1" accesskey="F">


You can't bind to events that happen where you have no control - e.g. the window chrome. The way most webapps deal with this is asking the user to confirm their decision to leave the page, using the onbeforeunload event:

window.onbeforeunload = function (e) {    var str = 'Are you sure you want to leave this page?';    e = e || window.event;    if (userHasSomeUnsavedWork) {        e.returnValue = str;        return str;    }}