Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Escape key = browser back button

In a browser how can I make the keyboard's escape key go back in Javascript.

For example: if you visit this page and click the "Fullscreen" link I'd like to press the escape key and go back to the previous page.

What's the Javascript to make this magic happen?

like image 944
Ryan Avatar asked Jun 17 '11 18:06

Ryan


3 Answers

You can add a Key-Listener:

window.addEventListener("keyup", function(e){ if(e.keyCode == 27) history.back(); }, false);

This will call history.back() if the Escape key (keycode 27) is pressed.

like image 128
Floern Avatar answered Oct 31 '22 19:10

Floern


$(document).bind("keyup", null, function(event) {
        if (event.keyCode == 27) {  //handle escape key
            //method to go back            }
    });
like image 30
Avien Avatar answered Oct 31 '22 19:10

Avien


You can bind an onkeyup event handler to window and check if the keycode is 27 (keycode for Escape), then use the window.history.back() function.

window.onkeyup = function(e) {
  if (e.keyCode == 27) window.history.back();
}

MDC docs on window.history, https://developer.mozilla.org/en/DOM/window.history

like image 23
basicxman Avatar answered Oct 31 '22 17:10

basicxman