Fullscreen API JavaScript Code Examples and Specification

Published :
Author :
Adam Khoury

Making documents and specific parts of the document toggle in and out of fullscreen mode is possible with the experimental Fullscreen API. We still have to apply browser specific prefixes which bloats the code a little bit, but it's not too difficult to make it work in all modern desktop browsers.

API Reference - https://fullscreen.spec.whatwg.org/

example 1 - full document fullscreen <style> body { position: absolute; top: 0px; left: 0px; margin: 0px; } #wrap { width: 100%; background: #FFF; padding: 40px; } </style> <script> var db, isfullscreen = false; function toggleFullScreen(){ db = document.body; if(isfullscreen == false){ if(db.requestFullScreen){ db.requestFullScreen(); } else if(db.webkitRequestFullscreen){ db.webkitRequestFullscreen(); } else if(db.mozRequestFullScreen){ db.mozRequestFullScreen(); } else if(db.msRequestFullscreen){ db.msRequestFullscreen(); } isfullscreen = true; wrap.style.width = window.screen.width+"px"; wrap.style.height = window.screen.height+"px"; } else { if(document.cancelFullScreen){ document.cancelFullScreen(); } else if(document.exitFullScreen){ document.exitFullScreen(); } else if(document.mozCancelFullScreen){ document.mozCancelFullScreen(); } else if(document.webkitCancelFullScreen){ document.webkitCancelFullScreen(); } else if(document.msExitFullscreen){ document.msExitFullscreen(); } isfullscreen = false; wrap.style.width = "100%"; wrap.style.height = "auto"; } } </script> <body> <div id="wrap"> <h2>Fullscreen Desktop Application</h2> <h3>My web page with desktop fullscreen feature</h3> <button onclick="toggleFullScreen()" ontouchstart="toggleFullScreen()">Toggle Full Screen</button> </div> </body> example 2 - Fullscreen image gallery <script> var elem; function fullScreen(elem){ if( elem.requestFullScreen ){ elem.requestFullScreen(); } else if( elem.webkitRequestFullscreen ){ elem.webkitRequestFullscreen(); } else if( elem.mozRequestFullScreen ){ elem.mozRequestFullScreen(); } else if( elem.msRequestFullscreen ){ elem.msRequestFullscreen(); } } </script> <body> <div id="wrap"> <h2>Fullscreen image gallery</h2> <img src="1.jpg" onclick="fullScreen(this)"><br><br> <img src="2.jpg" onclick="fullScreen(this)"><br><br> <img src="3.jpg" onclick="fullScreen(this)"> </div> </body>