Closing a help window when ESC is pressed

The help page closes when ESC is pressed or when it loses focus.

How to see the demo

Click here to open the help window: open help window. Then, click outside the help window or press ESC.


function closeHelp() {
var key = event.keyCode;
if (key == 27) window.close();

<body onBlur="javascript:window.close()" onKeyPress="closeHelp()">

How it works

This script uses the onBlur event to see if the window loses focus and the onKeyPress event to see if the ESC key is pressed (ASCII value 27). If either event occurs, the window is closed.

A script cannot close a window that was opened by the user without requesting the user's permission. However, a script can close a window (like this help window) without the user's permission.

This script can be modifed to use other keys. See the keypress demo to find the ASCII value of another key.

Browser compatibility

This script should work in any browser.


Just send us an email.