We all know the Web is an immensely powerful distraction machine, so sometimes providing an option to focus only on the content at hand is useful. This functionality is provided by the Fullscreen API, which allows you to expand any element to fill the entire screen of the device, rather than just the browser viewport. This is especially handy for large-screen devices, for instance, when playing video to provide the “lean back” experience of television.
Before setting up this script, check whether the browser has a full-screen mode. You can do this with the Boolean fullScreenEnabled attribute:
if (document.fullScreenEnabled) { … }
Fullscreen mode is called with the requestFullScreen() method. As this introduces potential security risks (an often-quoted example is an attack website that fools you into thinking that you’re seeing something else and copies your keystrokes), many devices provide an on-screen prompt to make sure you give permission to enter fullscreen mode. If you grant that permission, the element the method is called on scales up to 100 percent of the device screen’s height and width.
In the next code snippet, a click event listener is applied to the element #trigger, which, when fired, will put .target into fullscreen mode, as long as permission is granted. You can see this for yourself in the file fullscreen.html, which is illustrated in Figure 6-4.
var el = document.querySelector('.target'), launch = document.getElementById('trigger');
launch.addEventListener('click', function () {
el.requestFullScreen();
}, false);
The browser should offer a means to exit fullscreen mode, but you can also provide your own with the exitFullScreen() method. The next code block shows a function that uses this method to leave fullscreen mode when the ENTER key is pressed. Note two further things in the code: First, it uses the fullscreenchange event, which is fired whenever an element enters or leaves fullscreen mode; and second, it relies on an if statement using the fullScreenElement attribute, which returns either information about the element that is in fullscreen mode or null if there is none.
document.addEventListener('fullscreenchange', function () {
if (document.fullScreenElement !== null) {
document.addEventListener('keydown', function (e) {
if (e.keyCode === 13) {
document.exitFullScreen();
}
}, false);
}
}, false);
When an element has been put in fullscreen mode, you might want to style it (or its children) a little differently. It’s proposed that you can do this with a new dedicated CSS pseudo-class, which will be called either :fullscreen or :full-screen:
.target:full-screen {}