Key code does not hold the ESC key

Asked

Viewed 2,135 times

4

I’m doing a function, so that when you press a key on the keyboard, it performs another function. With the keys of letters, numbers and even Enter works. But the ESC key does not work. Has anyone ever had to do anything like this?

Follows code:

document.addEventListener('keypress', function(event){
    console.log(event.keyCode)
    if(event.keyCode == 27) {
        vm.fecha_modal();  
    }
})
  • 1

    Try asssim $(Document). keyup(Function(e) { if (e. keycode == 13) $('. save'). click(); // enter if (e. keycode === 27) $('. Cancel'). click(); // Esc });

  • @Paulohdsousa worked out! if you want you can put as answer

2 answers

5


Try it like this

$(document).keyup(function(e) { 
    if (e.keyCode === 27) 
        vm.fecha_modal(); 
}); 

2

I recommend to use the function below getCharCode to redeem the event code and then perform the treatment. The reason you have created this function is, in some browsers rescues the value of the event code with keyCode, in others with which.

So I’ve created a wrapper for both of you, so you’ll have a better browser compatibility. To view the code of each key, click on the field and press the keys.

I put a console.log to present the results. With the code in hand, just listen to events as our colleagues informed or even follow the example of this code.

function getCharCode(e) {
  e = (e) ? e : window.event, charCode = null;

  try {
    charCode = (e.which) ? e.which : e.keyCode;
    return charCode;
  } catch (err) {
    return charCode;
  }
}

$(function() {
  $('input').on('keyup', function(e) {
    console.log("Tecla pressionada %s (%s)", e.key, getCharCode(e));
  });
});
input {
  height: 100px;
  font-size: 40px;
  line-height: 100px;
  max-width: 100%;
  width: 100%;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input value="" placeholder="Clique aqui e pressione as teclas" />

Browser other questions tagged

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