MrThunder
MrThunder

Reputation: 745

Toggle fullscreen API with a single button

I have the fullscreen API working on the click of one button and exiting fullscreen on the click of another button. I would like to have the fullscreen toggle open and close with a single button.

 var requestFullscreen = function(ele) {
    if (ele.requestFullscreen) {
        ele.requestFullscreen();
    } else if (ele.webkitRequestFullscreen) {
        ele.webkitRequestFullscreen();
    } else if (ele.mozRequestFullScreen) {
        ele.mozRequestFullScreen();
    } else if (ele.msRequestFullscreen) {
        ele.msRequestFullscreen();
    } else {
        console.log('Fullscreen API is not supported.');
    }
};

var exitFullscreen = function() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
    } else {
        console.log('Fullscreen API is not supported.');
    }
};

var fsDocButton = document.getElementById('fs-doc-button');
var fsExitDocButton = document.getElementById('fs-exit-doc-button');

fsDocButton.addEventListener('click', function(e) {
    e.preventDefault();
    requestFullscreen(document.documentElement);
});

fsExitDocButton.addEventListener('click', function(e) {
    e.preventDefault();
    exitFullscreen();
});
<button id="fs-doc-button">FULLSCREEN</button>
<button id="fs-exit-doc-button">EXIT FULLSCREEN</button>

Upvotes: 0

Views: 1645

Answers (2)

var fsDocButton = $('#fs-doc-button');
fsDocButton.data('toggleState', 'first');

fsDocButton.on('click', function(e) {
    e.preventDefault();
    if ($(this).data('toggleState') == 'first'){
        requestFullscreen(document.documentElement);
        $(this).data('toggleState', 'second');
    }
    else{
        exitFullscreen();
        $(this).data('toggleState', 'first');
    }
});

$(document).keydown(function(e){
    if (e.keyCode == 27){
        $('#fs-doc-button').data('toggleState', 'second');
    }
});

Upvotes: 3

Kaiido
Kaiido

Reputation: 136658

Others are right in that you need some sort of a boolean to detect weither you should cancel or request the fullscreen.

But none takes into account that your users may cancel the fullscreen mode without using your button.

The only cross-browser way to check if you're in fullscreen already is to check for the document.fullcreenElement. If non-null, you're already in fullscreen and should exit it.

var isFullScreened = function(){
  return document.fullscreenElement ||
    document.mozFullScreenElement ||
    document.webkitFullscreenElement ||
    document.msFullscreenElement;
};
...
if(isFullScreened()){
  exitFs()
}
else{
  enterFS();
}

Upvotes: 1

Related Questions