Execute onclick of ESC Key

24.6k Views Asked by At

Briefly, my problem is that I would like to execute the effect of Esc button by a line of Javascript, for example execute an effect onclick of the Esc button. How can I do It ?

[ What I have is an upload in a jQuery box, so I would like that when the upload will finish, the escape function will be executed automatically to close the box]

2

There are 2 best solutions below

0
On

I know it's an old question. However if somebody lands in here on search, it may help:

First, trigger the event on desired element (or document),

$('a[name=close]').click(function(){
    var e = jQuery.Event("keyup"); // or keypress/keydown
    e.keyCode = 27; // for Esc
    $(document).trigger(e); // trigger it on document
});

And then, have a keyup listener on document:

// Esc key action
$(document).keyup(function(e) {
    if (e.keyCode == 27) { // Esc
        window.close(); // or whatever you want
    }
});
1
On

This code works for me

$(document).keyup(function(e) {     
    if(e.keyCode== 27) {
        alert('Esc key is press');  
    } 
});