Fullscreen Button
April 5, 2022
Above is an ultra basic fullscreen button demo / example (see the button in the top right).
You can also right-click on the link above and select ‘Save Link As…’ (or similar) to download the entire demo as a single html file.
The basic gist of the code (included below) is that it will add the fullscreen button html element to the document, but only if fullscreen is supported by the device (for example, currently fullscreen is not supported on IOS). When clicked the button will toggle the fullscreen mode while adding or removing a custom ‘fullscreen’ attribute on the document body. CSS then uses the attribute to show or hide the appropriate SVG in the button element.
Anyway, here is the Javascript:
if (document.fullscreenEnabled) {
const fullscreen_button = document.createElement("button");
fullscreen_button.setAttribute('id','fullscreen-button');
fullscreen_button.addEventListener("click", toggle_fullscreen);
fullscreen_button.innerHTML = `
<svg viewBox="0 0 24 24">
<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12
7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>
</svg>
<svg viewBox="0 0 24 24">
<path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6
11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/>
</svg>
`;
document.body.appendChild(fullscreen_button);
}
function toggle_fullscreen() {
if (!document.fullscreenElement) {
document.body.requestFullscreen();
document.body.setAttribute("fullscreen","");
} else {
document.exitFullscreen();
document.body.removeAttribute("fullscreen");
}
}
And here is the CSS:
body, ::backdrop {
background: #fff;
}
#fullscreen-button {
position: absolute;
top: 15px;
right: 15px;
background: rgba(0,0,0,0.05);
border: 0;
width: 40px;
height: 40px;
border-radius: 50%;
box-sizing: border-box;
transition: transform .3s;
cursor: pointer;
display: flex;
flex-direction: column;
justify-content: center;
}
#fullscreen-button:hover {
transform: scale(1.125);
}
#fullscreen-button svg:nth-child(2) {
display: none;
}
[fullscreen] #fullscreen-button svg:nth-child(1) {
display: none;
}
[fullscreen] #fullscreen-button svg:nth-child(2) {
display: inline-block;
}
Please note, you will notice in the CSS that I have included the pseudo selector for ‘::backdrop’, only because by default fullscreen elements have a black background and this can catch you out a bit if you’re not prepared for it. Chances are you won’t need that bit. Also, recently I decided to tweak my previous code to no longer include vendor prefixes which may not suit you if you want to offer the maximum support for older browsers etc.
If you liked this resources please consider showing your appreciation and offering your support. It will make my day!
Buy me a coffee