Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle ESC keydown on javascript popup window

I have a javascript window.open popup, and I want the popup to close itself when the user presses the ESC key. I can't figure out how to hook the keydown event (and on what object?) so that I can catch the ESC key.

I'm using jQuery.

like image 1000
Andrew Arnott Avatar asked Sep 26 '09 16:09

Andrew Arnott


5 Answers

Try something like this:

$(document).keydown(function(e) {
    // ESCAPE key pressed
    if (e.keyCode == 27) {
        window.close();
    }
});
like image 79
Gumbo Avatar answered Nov 02 '22 22:11

Gumbo


It is possible to achieve with JS Without using jQuery.

window.onkeydown = function( event ) {
    if ( event.keyCode == 27 ) {
        console.log( 'escape pressed' );
    }
};
like image 39
user3874938 Avatar answered Nov 02 '22 23:11

user3874938


event.key === "Escape"

No more arbitrary number codes!

document.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; in ES6+
    if (key === "Escape") {
        window.close();
    }
});

Mozilla Docs

Supported Browsers

like image 22
Gibolt Avatar answered Nov 02 '22 22:11

Gibolt


Remember that you must use the function @Gumbo posted in the popup-window... So you will need to include JQuery in the popup and execute the function there, not the window that opens the popup.

like image 4
PatrikAkerstrand Avatar answered Nov 02 '22 23:11

PatrikAkerstrand


To handle both esc and enter key on dialog window.onkeydown = function(event) {

if(event.keyCode===27|| event.keyCode===13){
   window.close();
}
}
like image 2
Mukesh Kumar Avatar answered Nov 03 '22 00:11

Mukesh Kumar