Tom Tucker
Tom Tucker

Reputation: 11906

Overriding Browser's Keyboard Shortcuts

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?

Upvotes: 60

Views: 71067

Answers (4)

deepeshb
deepeshb

Reputation: 81

Here is my Solution:

document.onkeydown = function () {
                       if ((window.event.keyCode == 121) && (window.event.ctrlKey))) {
               window.event.returnValue = false;
               window.event.cancelBubble = true;
               window.event.keyCode = 0;
               return false;
           }
       }

Upvotes: 1

Alesk
Alesk

Reputation: 157

Here is my solution to this problem:

Most (if not all) of the browser's shortcuts will be overriden. Only system ones, like Alt + Tab or the Windows key won't.

document.onkeydown = overrideKeyboardEvent;
document.onkeyup = overrideKeyboardEvent;
var keyIsDown = {};

function overrideKeyboardEvent(e){
  switch(e.type){
    case "keydown":
      if(!keyIsDown[e.keyCode]){
        keyIsDown[e.keyCode] = true;
        // do key down stuff here
      }
    break;
    case "keyup":
      delete(keyIsDown[e.keyCode]);
      // do key up stuff here
    break;
  }
  disabledEventPropagation(e);
  e.preventDefault();
  return false;
}
function disabledEventPropagation(e){
  if(e){
    if(e.stopPropagation){
      e.stopPropagation();
    } else if(window.event){
      window.event.cancelBubble = true;
    }
  }
}

Upvotes: 16

Brad Robinson
Brad Robinson

Reputation: 46797

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).

Upvotes: 20

antimatter15
antimatter15

Reputation: 1456

onkeydown = function(e){
  if(e.ctrlKey && e.keyCode == 'S'.charCodeAt(0)){
    e.preventDefault();
    //your saving code
  }
}

Upvotes: 48

Related Questions