Categories:

Displaying Content in Full Screen using the Fullscreen API in JavaScript

Created: June 8th, 17'

Some content just beg to be displayed full screen, such as select images or videos on your site. When I say full screen, I mean occupying the entire user screen, without any of the browser chrome or even background applications getting in the way. With the Fullscreen API, with just a few lines of JavaScript code, you can turn the spotlight on any deserving piece of content on your site, say that spectacular shot of the coast you're so proud of and just posted on your travel blog (photo credits: PixaBay):

JavaScript Full Screen API example- opening an image

Opening an element in Full Screen

At the heart of the fullscreen API is the requestFullscreen() method, which can be called on any element in the document to make it go kaboom:

Var featuredimg = document.getElementById("rockyshot")
If (featuredimg.requestFullscreen){
	featuredimg.requestFullscreen() 
}

The FullScreen API is supported in IE 11+ and all modern versions of Chrome and Firefox on the desktop. The caveat is that at the time of writing, prefixes are still needed to access the supported version of the relevant methods and event handlers that make up the API. For the main requestFullscreen() method for example, the following 3 additional versions exist to cater to the 3 major browsers:

requestFullscreen() (standard version)
webkitRequestFullscreen()
mozRequestFullScreen()
msRequestFullscreen()

Cross Browser requestFullscreen() method

Cross Browser Full Screen Function: Let's create a cross browser version of requestFullscreen() we can use on any element on the page so we don't get lost in a sea of if/else statements each time we use it:

function getreqfullscreen(){
	var root = document.documentElement
	return root.requestFullscreen || root.webkitRequestFullscreen || root.mozRequestFullScreen || root.msRequestFullscreen
}
//usage: getreqfullscreen().call(targetelement) // open full screen on targetelement

When we call getreqfullscreen(), we get the supported version of requestFullscreen() in the browser. To call the actual method then, we invoke call() on top of it to give the method the desired context, by passing into call() the element we with to make full screen.

Example: Lets get all images on a page with CSS class "canfullscreen" to go full screen when clicked on (photo credits: PixaBay):

var globalreqfullscreen = getreqfullscreen() // get supported version of requestFullscreen()
	document.addEventListener('click', function(e){
	var target = e.target
	if (target.tagName == "IMG" && target.classList.contains('canfullscreen')){
		globalreqfullscreen.call(target) 
	}
}, false)

Easy as pie!

Note: To call requestFullscreen() on the document itself to make the entire page full screen, use document.documentElement.requestFullscreen(), or with the cross browser function, globalreqfullscreen.call(document.documentElement)

Exiting from Full Screen

When an element is placed in full screen, the user by default has the option to exit from it by pressing "esc" or "f11". You can also do the same on demand with document.exitFullscreen() and its diabolical siblings:

document.exitFullscreen() (standard version)
document.webkitExitFullscreen()
document.mozCancelFullScreen()
document.msExitFullscreen()

Notice that unlike the requestFullscreen() method, which exists on each DOM element to enter it into full screen, the exitFullscreen() method is defined only on the document object to take the element back to normal space when called.

Cross Browser Exit Function: Like in the previous section, we'll create a function that returns the browser supported version of document.exitFullscreen() for our convenience:

function getexitfullscreen(){
	return document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen || document.msExitFullscreen
}
//usage: getexitfullscreen.call(document) //always pass document into it

Example: In the following, we add to the previous example so double clicking on any image with CSS class "canfullscreen" returns the browser back to normal mode:

var globalexitfullscreen = getexitfullscreen() // get supported version of exitFullscreen()
document.addEventListener('dblclick', function(e){
	var target = e.target
	if (target.tagName == "IMG" && target.classList.contains('canfullscreen')){
		globalexitfullscreen.call(document)
	}
}, false)

Checking for full screen mode

Whenever the browser goes into full screen mode, the document.fullscreenElement object (read only) contains a reference to the target element currently being shown. This object returns null in all other cases.

Using document.fullscreenElement, we can:

  • Check if the browser is currently in full screen mode
  • Check which element is being shown

document.fullscreenElement like other Full Screen API related methods is also prefixed depending on the browser:

document.fullscreenElement (standard version)
document.webkitFullscreenElement
document.mozFullScreenElement
document.msFullscreenElement

Yes this is starting to be a real pain in the beeeehind, but lets just roll with the punches.

Cross Browser Get Full Screen Element Function : Use the following function to return the supported document.fullscreenElement object:

function getfullscreenelement(){
	return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement
}
//usage: getfullscreenelement()

The below checks whether the browser is currently in full screen, and if an image is front and center:

If (getfullscreenelement() && getfullscreenelement().tagName == "IMG"){
	console.log("An image is currently being shown full screen")
}

Toggling an element between fullscreen and regular mode

A common use of the document.fullscreenElement object is to write code that dynamically toggles an element between fullscreen and regular mode.

Example: To illustrate, the following uses a single click action on an image to toggle it between full screen and regular mode depending on which mode the browser is currently in:

var globalreqfullscreen = getreqfullscreen() // get supported version of requestFullscreen()
var globalexitfullscreen = getexitfullscreen() // get supported version of document.exitFullscreen()

document.addEventListener('click', function(e){
	var target = e.target
	if (target.tagName == "IMG" && target.classList.contains('canfullscreen')){
		if (getfullscreenelement() == null){ // if browser is currently not in full screen
			globalreqfullscreen.call(target)
		}
		else{
			globalexitfullscreen.call(document)
		}
	}
}, false)

Other methods and event handlers

A few other objects and event handlers complete the Full Screen API. They are:

  • document.fullscreenEnabled: Boolean that returns true if the page is available for full screen mode. Windowed plugins or <iframe> elements without an explicit allowfullscreen attribute set will fail when attempting to open them in full screen. The document.onfullscreenerror event will fire instead in those instances.
  • document.onfullscreenchange: Event handler that fires whenever the browser enters or exits full screen mode.
  • document.onfullscreenerror: Event handler that fires when the browser cannot enter full screen mode when requested.

And yes, at this time, prefixes must be used to access the corresponding versions of everything listed above. Here they are:

document.fullscreenEnabled (standard) document.onfullscreenchange (standard) document.onfullscreenerror (standard)
document.webkitFullscreenEnabled document.onwebkitfullscreenchange document.onwebkitfullscreenerror
document.mozFullScreenEnabled document.onmozfullscreenchange document.onmozfullscreenerror
document.msFullscreenEnabled document.onmsfullscreenchange document.onmsfullscreenerror

To create cross browser versions of document.onfullscreenchange and document.onfullscreenerror, a simple but elegant approach is to first see which version of the requestFullscreen() method the browser supports, and then map the result to the corresponding version of the event handler we wish to use.

Cross Browser onfullscreenchange event: Here's one way to create a unified document.onfullscreenchange event handler:

function getonfullscreenevt(){
	var root = document.documentElement
	var fullscreenevts = {
		'requestFullscreen': 'onfullscreenchange',
		'webkitRequestFullscreen': 'onwebkitfullscreenchange',
		'mozRequestFullScreen': 'onmozfullscreenchange',
		'msRequestFullscreen': 'onmsfullscreenchange'
	}
	
	for (var method in fullscreenevts){
		if (root[method]){ // if root document object supports this requestFullscreen method
			return fullscreenevts[method] // return corresponding onfullscreenchange event string
		}
	}
	return undefined
}
//usage: var globalonfullscreenchange = getonfullscreenevt(); document[globalonfullscreenchange] = function(){...}

When we call getonfullscreenevt(), we get the supported version of "onfullscreenchange" back, such as "onwebkitfullscreenchange". Then, to utilize this event string, we associate it with the document object, the object the event is defined under, and assign a function to it:

var globalonfullscreenchange = getonfullscreenevt()

document[globalonfullscreenchange] = function(){
	console.log('You just entered or exited full screen')
}

Note that using document.addEventListener() currently doesn't work with the "onfullscreenchange" or "onwebkitfullscreenchange" events- they need to be attached directly to the document object.

Full Screen related CSS

You can refine the look of an element when it is in full screen mode using the :fullscreen pseudo selector and its prefixed variants:

:-webkit-full-screen {
	/*style for full screen element */
}

:-moz-full-screen {
	/*style for full screen element */
}

:-ms-fullscreen {
	/*style for full screen element */
}

:fullscreen { /* official selector */
	/*style for full screen element */
}

They are immensely helpful when the style of the target element and its children need to be different from their default styles in normal mode, such as a FIGURE container with an image inside that you wish to make full screen:

Example:

An awesome picture
Hawaii, a U.S. state, is an isolated volcanic archipelago in the Central Pacific. Its islands are renowned for their rugged landscapes of cliffs, waterfalls, tropical foliage and beaches with gold, red, black and even green sands. -Wikipedia

The figure by default has a width of 300px, with the child image spanning the full width. When in full screen mode, however, we want the figure to expand to 100%; and the contained image to a height of 90vh (leaving some room for the caption below it). Here is the CSS that accomplishes this:

The CSS:

<style>

figure{
	width: 300px;
	background: #eee;
	padding: 5px;
	cursor: pointer;
}

figure img{
	width: 100%;
	height: auto;
}

figure:-webkit-full-screen {
	width: 100%;
	text-align: center;
}

figure:-moz-full-screen {
	width: 100%;
	text-align: center;
}

figure:-ms-fullscreen {
	width: 100%;
	text-align: center;
}

figure:fullscreen { /* official selector */
	width: 100%;
	text-align: center;
}

figure:-webkit-full-screen img{
	width: auto;
	height: 90vh;
}

figure:-moz-full-screen img{
	width: auto;
	height: 90vh;
}

figure:-ms-fullscreen img{
	width: auto;
	height: 90vh;
}

figure:fullscreen img{
	width: auto;
	height: 90vh;
}

</style>

Conclusion

Displaying certain content as full screen can be just the extra "oomph" you need to impress and convert your visitors, such as for product images on an ecommerce site. With the Full Screen API, there is now a way to do that.