Norris
Norris

Reputation: 91

Press ESC to close popup window for Google Chrome

I have this function for closing popup window by pressing the ESC escape key. However it is not working for Google Chrome. I don't know what is missing; does anyone have a solution ?

function doClose(e) 
{
    if (!e) e = window.event; 

    if (e.keyCode) 
    {
        if (e.keyCode == "27") window.close();
    }
    else if (e.charCode) 
    {
        if (e.keyCode == "27") window.close();
    }
}
document.onkeypress = doClose;

Upvotes: 2

Views: 5580

Answers (2)

Matty F
Matty F

Reputation: 3783

onkeypress does not capture some keys - mainly system keys like ESC and F1 -> F12, use onkeydown instead. Also there's a bug in your logic, update to:

function doClose(e) 
{
    if (!e) e = window.event; 

    if (e.keyCode) 
    {
        if (e.keyCode == "27") window.close();
    }
    else if (e.charCode) 
    {
        if (e.charCode == "27") window.close();
    }
}
document.onkeydown = doClose;

Upvotes: 3

Related Questions