Keyup event should not activate with special keys

Asked

Viewed 65 times

1

In my document I am creating some keyboard shortcuts to facilitate the use of the page itself, and I am doing it as follows:

$(document).on("keyup", function(e){
    /*Tecla C*/
    if(e.which === 67){
       alert("A tecla C foi pressionada");
    }
});

Above when the C is pressed the page should perform an action, but how to handle the special keys, as the way it is if the user presses CTRL + C, the event will be activated, how can I prevent this from happening with this shortcut and with the various other keyboard patterns? If possible I would not like to have to disable such default keyboard events / operating system.

2 answers

2


If I understand what you want, an alternative would just call certain event if the key C is triggered without any combination, in other words, the event is triggered only if you click only the key C

var keys = [];

$(document).keydown(function (e) {
    keys.push(e.which);
});

$(document).on("keyup", function(e){
    /*Tecla C*/
    if(e.which === 67 && keys.length == 1){
       alert("A tecla C foi pressionada");
       //...evento...
    }
    keys = []
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • Perfect, it’s exactly what I need <3

0

You can use the properties:

  • metaKey to identify if the Windows key or Command (OSX) has been pressed.
  • altKey to identify if the alt key is pressed
  • ctrlKey to identify if the control key is pressed

I created a fiddle example with the passage below:

  $('#teste').on("keyup", function(event){

    if(event.metaKey) {
        $("#status").html("Metakey pressionada");
    }

    if(event.altKey) {
        $("#status").html("Tecla alt pressionada");
    }

    if(event.ctrlKey) {
        $("#status").html("Tecla control pressionada");
    }

  });

Browser other questions tagged

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