KeyUP event should not activate with special keys

1

In my document I'm creating some shortcuts on the keyboard to make it easier to use the page itself, and I'm doing it as follows:

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

Above when C is pressed the page should perform an action, but how to handle the special keys, because of 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 want to have to disable such keyboard / OS default events.

    
asked by anonymous 12.05.2017 / 16:20

2 answers

2

If I understand what you want, an alternative would be to just call an event if the C key is triggered without any combination, in other words, the event is only triggered by clicking the < kbd> 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>
    
12.05.2017 / 16:38
0

You can use the properties:

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

I've created a sample fiddle with the excerpt 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");
    }

  });
    
12.05.2017 / 16:46