Program ESC key in JavaScript for IE 11

0

Good morning everyone, I have a problem with a script that works in Chrome but not in Internet Explorer, the script redirects when you press the Esc button (27) using the event.keycode lei that is not compatible with IE11, how could I work with that browser and still work in Chrome?

My Script

    <script>
document.body.addEventListener("keydown", function (event) {
    if (event.keyCode === 27) {
        window.location.replace("http://localhost:51213/Default.aspx");
    }
});
</script>
    
asked by Hans 05.12.2017 в 13:27
source

2 answers

2

Capturing the event at the level of document instead of body should work on both.

You should also change the window.location.replace(url) by 'window.location.href = url':

document.addEventListener("keydown", function (event) {
  if (event.keyCode === 27) {
      alert('Esc pulsado');
      window.location.href='https://pildorasdotnet.blogspot.com';
  }
});
    
answered by 05.12.2017 в 13:39
1

The Event.keyCode property is deprecated and you should instead use Event.code

Example:

document.body.addEventListener("keydown", function(event) {
  console.log(event.code, event.keyCode);
  if (event.code === 'Escape' || event.keyCode === 27) {
    // Aqui la lógica para el caso de Escape ...
    alert('Esc!');
  }
});
Presiona cualquier tecla para ver el resultado

PD : window.location.replace("http://localhost:51213/Default.aspx"); so do not take any action.

If you want to redirect to said URL you should do it like this:

window.location.href = "http://localhost:51213/Default.aspx";
    
answered by 05.12.2017 в 13:55