Short circuit in JS stopping on first input

90 views Asked by At

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

2

There are 2 answers

1
T.J. Crowder On BEST ANSWER

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.

0
Shilly On

The problem is that you're already calling the function, so if it doesn't exist, you get an error. You coudl try something like:

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