JavaScript - Fullscreen mode toggle button
A JavaScript code example for implementing a button to toggle fullscreen mode.
The HTML has a button with id "full-screen-btn" to toggle fullscreen.
<button type="button" id="full-screen-btn">Full Screen Mode</button>
The click event of the fullscreen toggle button is implemented with addEventListener()
.
"document.fullscreenElement" gets the current fullscreen state.
It returns "true" if in fullscreen mode, "false" otherwise.
document.documentElement.requestFullscreen()
enables fullscreen mode.
document.exitFullscreen()
disables fullscreen mode.
// Fullscreen mode toggle button
document.querySelector('#full-screen-btn').addEventListener('click', function () {
// Toggle based on current state
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen();
} else {
document.exitFullscreen();
}
}, false);