Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Fullscreen Button

I'm trying to build a fullscreen button clickable with a

<a href="" class="off" id="fullscreenBtn" onclick="this.className='on';return false;">Fullscreen<div class="hint">Click F11</div></a>

Unfortunately I can't exit the fullscreen mode by clicking on the button again which would be ideal.

The JS looks like this

jQuery("#fullscreenBtn").click(function () {
        var
            el = document.documentElement
            , rfs =
                el.requestFullScreen
                    || el.webkitRequestFullScreen
                    || el.mozRequestFullScreen
            ;
        rfs.call(el);
    });

I didn't write this on my own but I have to maintain the code, so I'd be very glad over a little explanation.

Dave

2 Answers

Try adding some conditional logic...

jQuery("#fullscreenBtn").click(function () {
      if (!document.fullscreenElement &&    // alternative standard method
      !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) {
      var
            el = document.documentElement
            , rfs =
                el.requestFullScreen
                    || el.webkitRequestFullScreen
                    || el.mozRequestFullScreen
            ;
        rfs.call(el);
        }
        else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    }
  }
    });

taken from : using fullscreen mode

working codepen

Thanks Andrew,

I was trying some conditions but just wasn't able to write a working code. Thanks a lot for your help!