Enter fullscreen mode using javascript

javascript-fullscreen

One thing that we had not been able to do before with JavaScript is to allow the user to enter full screen mode with the click of a button, just using JavaScript. That has changed with some of the newer browsers.

We had a request a few weeks ago, where the user wanted to display a gallery in full screen mode, but did not want to use Flash. The user wanted to fill the whole computer screen not just the browser window; below is the code we used to accomplish the task.

Note: the code will work only a few browsers (Chrome 15+, Morzilla 10+, Safari 5.1+ ) eventually all browsers should support it according to W3C documentation.

 

The Code

Add this code on top of your JavaScript file or a separate file; this will toggle Full Screen mode for the browsers mentioned above.

<script type="text/javascript">
function toggleFullScreen() {
  if ((document.fullScreenElement && document.fullScreenElement !== null) ||    // alternative standard method
      (!document.mozFullScreen && !document.webkitIsFullScreen)) {               // current working methods
    if (document.documentElement.requestFullScreen) {
      document.documentElement.requestFullScreen();
    } else if (document.documentElement.mozRequestFullScreen) {
      document.documentElement.mozRequestFullScreen();
    } else if (document.documentElement.webkitRequestFullScreen) {
      document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
    }
  } else {
    if (document.cancelFullScreen) {
      document.cancelFullScreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitCancelFullScreen) {
      document.webkitCancelFullScreen();
    }
  }
}
</script>

After that all you have to do is to call the function

<script type="text/javascript"> toggleFullScreen();</script>

Using the enter/return key

<script type="text/javascript"> 
document.addEventListener("keydown", function(e) {
  if (e.keyCode == 13) {
    toggleFullScreen();
  }
}, false);
</script>

Using the “ESC” key to exit fullscreen mode

<script type="text/javascript"> 
document.addEventListener("keydown", function(e) {
 if (e.keyCode == 27) {
    if (document.cancelFullScreen) {
      document.cancelFullScreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitCancelFullScreen) {
      document.webkitCancelFullScreen();
    }
 }
 document.location = jQuery('.galleria-thumblink').attr('href');
}, false);
</script>

Using jQuery

<script type="text/javascript"> 
jQuery(SELECTOR).click(function(){
	toggleFullScreen();
});
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *