Capturing the ESC key using JavaScript only

html, html5-video, javascript

Solution

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

Problem

I have a custom video play with it's own controls. I have a script to make changes to the controls when the user enters and exists full screen. The problem is that when I exit fulls creen using the `ESC` key instead of the button, the style changes to the controls are not reverted back. I need to ensure that exiting full screen using `ESC` or button will result in the same behaviour. CSS: ``` function toggleFullScreen() { elem = document.getElementById("video_container"); var db = document.getElementById("defaultBar"); var ctrl = document.getElementById("controls"); if (!document.fullscreenElement && // alternative standard method !document.mozFullScreenElement && !document.webkitFullscreenElement) { // current working methods if (document.documentElement.requestFullscreen) { ctrl.style.width = '50%'; ctrl.style.left = '25%'; full.firstChild.src = ('images/icons/unfull.png'); elem.requestFullscreen(); } else if (document.documentElement.mozRequestFullScreen) { full.firstChild.src = 'images/icons/unfull.png'; ctrl.style.width = '50%'; ctrl.style.left = '25%'; elem.mozRequestFullScreen(); } else if (document.documentElement.webkitRequestFullscreen) { ctrl.style.width = '50%'; ctrl.style.left = '25%'; full.firstChild.src = 'images/icons/unfull.png'; elem.webkitRequestFullscreen(); } } else if (document.exitFullscreen) { full.firstChild.src = 'images/icons/full.png'; ctrl.style.width = '100%'; ctrl.style.left = '0'; document.exitFullscreen(); } else if (document.mozCancelFullScreen) { full.firstChild.src = 'images/icons/full.png'; ctrl.style.width = '100%'; ctrl.style.left = '0'; document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { ctrl.style.width = '100%'; ctrl.style.left = '0'; full.firstChild.src = 'images/icons/full.png'; document.webkitCancelFullScreen(); } } ```

Original source