kdjernigan kdjernigan - 8 months ago 38
Javascript Question

Javascript - How to make escape key change url?

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

The previous code is a code I found that determines if the escape key is pressed and released; however, I've never used code like this before.

  1. I was wanting to find out if this was an okay code to use as far as security and performance?

  2. I wanted to find out how to make this change the page url? Basically, when they press the esc key and let go, it changes to the login page.

  3. Is there a better way to do this?


You can change the current url when pressing the esc button like so:

window.onkeyup = function(e) {
    var event = e.which || e.keyCode || 0; // .which with fallback

    if (event == 27) { // ESC Key
        window.location.href = 'YOURURL'; // Navigate to URL

Alternatively, you could use jQuery's $(window).keyup() the same way.

Here we add an event listener to onkeyup to check for user interaction with the keyboard. When the user presses down and then releases a key the event will fire.

We then check if the key is the ESC key (27). Key code 27 (when using .which) is supported by the most popular browsers (Chrome, Safari, Firefox, Opera, IE).

On a final note. To prevent any default action you can return false; on keydown or keypress; as explained here.