Creating keyboard shortcuts for your HTML5 app?

11,177

Well, that one works for me: (CTRL-S in Chrome)

$(document).keydown(function(evt){
    if (evt.keyCode==83 && (evt.ctrlKey)){
        evt.preventDefault();
        alert('worked');
    }
});
Share:
11,177
MaiaVictor
Author by

MaiaVictor

Updated on June 04, 2022

Comments

  • MaiaVictor
    MaiaVictor almost 2 years

    How to create keyboard shortcuts for HTML5 apps? Using key events don't work because some browsers already define most of those inputs for built-in features such as Save As..., (which are useless for interactive apps).

  • lordvlad
    lordvlad about 11 years
    yes, the key is to use event.preventDefault(). still, some shortcuts wont work in some browsers while others wont work in other browsers
  • apoq
    apoq about 11 years
    I see your point, ctrl-s will fire up save dialog with an alert in FF, but as Juan Mendes mentioned above, you either should use shortcuts that are not used in any browser, or have aliases for your hotkeys for different browsers. I definetly can't see any other way, as a web app can't override built-in functions. Perhaps you should look into writing plugins for that.
  • MaiaVictor
    MaiaVictor about 11 years
    Sure, event.preventDefault() is indeed the key point I was missing. Might I ask if I your solution is cross-browser (as in, on the specification)?
  • apoq
    apoq about 11 years
    no it's not. I think i've mentioned it in the comment above :)
  • www139
    www139 over 8 years
    It makes sense because keydown fires multiple times. Neat bit of code.
  • Supreme Dolphin
    Supreme Dolphin about 8 years
    shortcut.js is awfully slow. it makes typing a nightmare.
  • Supreme Dolphin
    Supreme Dolphin about 8 years
    use keypress instead since it is what the default browser event procedures use.