Search code examples
javascriptfullscreenshort-circuiting

Short circuit in JS stopping on first input


I'm having some problems trying to use short circuiting on a web page I am making.

I am trying to use

document.webkitExitFullscreen() || document.mozCancelFullScreen() || document.exitFullScreen();

But it seems to stop on the first try, despite that I would have though it would continue after the first argument comes up as undefined.

If I simply type in

document.mozCancelFullScreen()

then it works fine

http://i.imgur.com/rINs1kR.png

I was wondering if anyone could point me to what I'm doing wrong here The screenshot is taken in firefox btw. Thanks in advance


Solution

  • Your code is trying to call document.webkitExitFullscreen and if it returns a falsy value, call document.mozCancelFullScreen, etc.

    But if document.webkitExitFullscreen itself is undefined you'll get an error trying to call it, and the code will stop running at that point.

    Perhaps:

    var exitFullScreen = document.webkitExitFullscreen || document.mozCancelFullScreen || document.exitFullScreen;
    if (exitFullScreen) {
        exitFullScreen.call(document); // Just `exitFullScreen();` may work as well
    }
    

    Or alternatively:

    ["webkitExitFullscreen", "mozCancelFullScreen", "exitFullScreen"].some(function(name) {
        if (document[name]) {
            document[name]();
            return true;
        }
    });
    

    ...which avoids the whole "do I need call or not?" issue.