What is the best way to capture keyboard shortcuts?

Asked

Viewed 2,059 times

4

Currently I use the keypress approach to capture the Alt pressed and the key that the user wants, however using the Pressed alt can cause compatibility problems in some browsers.

For example, opening the search window:

$(document).on('keypress', function(e) {
  console.log(e.which); // Retorna o número código da tecla
  console.log(e.altKey); // Se o alt foi Pressionado retorna true
  if ((e.altKey) && (e.which === 112)) { // Pesquisar (Alt + P)
    document.write('Abriu Pesquisa.');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

This action in Firefox will work normally, but if it is used in Chrome it will open the print screen.

So the question is as follows, how can I create shortcuts that are safe independent of the browser used?

  • This is really tricky. The Alt is also used as hotkey for screen readers for visually impaired, among other features. Just one comment on the subject.

  • Is this what you’re looking for? -> http://jsfiddle.net/Sergio_fiddle/vexcuhu2/

  • @Pedrocamarajunior, of course, I have knowledge about this, I asked why there can be a better approach than this that avoids these problems :)

  • @Sergio exactly that :) so the magic should happen in keydown and not keypress?

  • @Highlander yes, and using the 80. I think that’s cross-browser...

1 answer

5


Use the event keydown and the code 80.

$(document).on('keydown', function(e) {
  console.log(e.which); // Retorna o número código da tecla
  console.log(e.altKey); // Se o alt foi Pressionado retorna true
  if ((e.altKey) && (e.which === 80)) { // Pesquisar (Alt + P)

http://jsfiddle.net/Sergio_fiddle/vexcuhu2/

I have already mentioned another answer differences between keydown and keypress. In this case, to find out whether the Alt was pressed you really have to use the keydown, as it is not correctly detected with the keypress on some browsers.

  • @Highlander completed the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.