views:

49

answers:

2

I'd like to add support for keyboard shortcuts to a couple of pages in my web application by intercepting the keypress event handler of the document object, not the accesskey attribute.

The problem is that every browser has its own keyboard combinations, so it's impossible to come up with a set of keyboard combinations that work on all web browsers and yet consistent.(e.g. It'd be silly if the shortcut for save was ctrl + shift + S while one for delete was alt + D.)

So I figured it would be just simpler to override browser shortcuts altogether in a couple of pages with mine.

All downside aside, is it possible? If so, how do you do it?

Thanks!

+2  A: 
onkeydown = function(e){
  if(e.ctrlKey && e.keyCode == 'S'.charCodeAt(0)){
    e.preventDefault();
    //your saving code
  }
}
antimatter15
In a lot of situations, I don't think that would work. With keys like 'tab', a lot of browsers will intercept the command before the script can alter the key's behavior correctly.
Trafalmadorian
`event.preventDefault` only works (when it does) on W3C compliant browsers, not (say) the dominant browser on the general web, Microsoft's -- unless, of course, you're using a library like jQuery that adds it in for you.
T.J. Crowder
T.J.> You mean jQuery can override keyboard shortcuts even on IE?
Tom Tucker
+2  A: 

There's an excellent coverage of this here: http://unixpapa.com/js/key.html

As for whether this is something that should be done, stackoverflow's question editor override's quite a few keys without disrupting too much (hover over the toolbar buttons).

cantabilesoftware