Capturing the ESC key using Javascript only

event.key === "Escape"

More recent and much cleaner: use event.key. No more arbitrary number codes!

document.addEventListener("keydown", function(event) {
    const key = event.key; // Or const {key} = event; in ES6+
    if (key === "Escape") {
        // Do things
    }
});

Modern style, with lambda and destructuring

document.addEventListener("keydown", ({key}) => {
    if (key === "Escape") // Do things
})

Mozilla Docs

Supported Browsers


Edit: This answer is outdated. For modern browsers, @Gibolt's answer is better. If you need to support IE11, you can fallback to the legacy event.keyCode. See this article for more details.

It sounds like you want to attach a keypress event to the document. Something like this ought to do the trick.

document.onkeypress = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        alert("Esc was pressed");
    }
};

For more info, check out this article