JavaScript - Detect fullscreen mode state
A JavaScript code example for detecting fullscreen mode state.
The HTML has a fullscreen toggle button with id "full-screen-btn" and an output element with id "output".
<button type="button" id="full-screen-btn">Full Screen Mode</button>
<p id="output">False</p>
An event triggered on fullscreen mode change can be created with addEventListener()
using "fullscreenchange".
The current fullscreen mode state is gotten with "document.fullscreenElement".
It returns "true" if in fullscreen mode, "false" otherwise.
// Fullscreen toggle button
document.querySelector('#full-screen-btn').addEventListener('click', function () {
// Toggle state on click
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen();
} else {
document.exitFullscreen();
}
}, false);
// Detect fullscreen change
document.addEventListener('fullscreenchange', () => {
// Check if fullscreen
if (document.fullscreenElement) {
document.querySelector('#output').textContent = 'True';
} else {
document.querySelector('#output').textContent = 'False';
}
}, false);