What is the best way to capture keyboard shortcuts?

3

I currently use the keypress approach to catch the Alt pressed and the key that the user wants, but using alt Pressed may cause compatibility issues in some browsers.

For example, by 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, how can I create shortcuts that are safe regardless of the browser used?

    
asked by anonymous 14.12.2015 / 19:15

1 answer

5

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

link

I've already mentioned another answer differences between keydown and keypress . In this case, to know if Alt has been pressed you even have to use keydown , since it is not detected correctly with keypress in some browsers .

    
14.12.2015 / 19:28