'Capturing the ESC key using JavaScript only
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();
}
}
Solution 1:[1]
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
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
