Key code does not hold the ESC key

5

I'm making a function so that when a keyboard key is pressed, it performs another function. With the letter keys, numbers and until Enter works. However, the ESC key does not work. Has anyone ever had to do something similar?

Follow the code below:

document.addEventListener('keypress', function(event){
    console.log(event.keyCode)
    if(event.keyCode == 27) {
        vm.fecha_modal();  
    }
})
    
asked by anonymous 10.08.2017 / 14:52

2 answers

5

Try it out

$(document).keyup(function(e) { 
    if (e.keyCode === 27) 
        vm.fecha_modal(); 
}); 
    
10.08.2017 / 14:59
2

I recommend using the function below getCharCode to retrieve the event code and then perform the treatment. The reason for having created this function is in some browsers it retrieves the value of the event code with keyCode , in others with which .

So I've created a wrapper for both, so it will have a greater compatibility of browsers. To view the code for each key, click on the field and press the keys.

I put console.log to display the results. With the code in hand, just listen to the events as our colleagues reported 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><inputvalue="" placeholder="Clique aqui e pressione as teclas" />
    
10.08.2017 / 15:16