IE Browser Mode and Document Mode onchange() - javascript

A client has a few machines set to different browser and document modes. This is affecting a Javascript function:
$(".jumpmenu").change(function() {
var val = $(this).val();
if (val != '') {
location.href=val;
}
});
The function does not run when this is the case. I have set my IE to the same and can confirm that the change does not happen.
My first question is why would an IT department set the browser and document modes differently.
Secondly is there anything I can do to quickly fix the problem without making them change their doc and browser modes?
regards.

Related

Detect if console/devtools is open in all browsers

I'm trying to create a script which will run when any browser console is opened or closed. Is there any way to detect if the browser console in all browsers (Firefox/IE/Chrome/Safari/Opera) is open or not via JavaScript, jQuery, or any other client-side script?
If you are willing to accept an interference for the user,
you could use the debugger statement, as it is available in all major browsers.
Side note: If the users of your app are interested in console usage, they're probably familiar with dev tools, and will not be surprised by it showing up.
In short, the statement is acting as a breakpoint, and will affect the UI only if the browser's development tools is on.
Here's an example test:
<body>
<p>Devtools is <span id='test'>off</span></p>
<script>
var minimalUserResponseInMiliseconds = 100;
var before = new Date().getTime();
debugger;
var after = new Date().getTime();
if (after - before > minimalUserResponseInMiliseconds) { // user had to resume the script manually via opened dev tools
document.getElementById('test').innerHTML = 'on';
}
</script>
</body>
devtools-detect should do the job. Try the simple demo page.
devtools-detect → detect whether DevTools is open, and its orientation.
Supported Browsers:
DevTools in Chrome, Safari, Firefox & Opera
Caveats:
Doesn't work if DevTools is undocked (separate window), and may show a false positive if you toggle any kind of sidebar.
I don't think it is directly possible in JS for security reasons.But in here
they are claiming that it is possible and is useful for when you want something special to happen when DevTools is open. Like pausing canvas, adding style debug info, etc.
But As #James Hill tell in this, I also thinks even if a browser chose to make this information accessible to the client, it would not be a standard implementation (supported across multiple browsers).
Also can also try this one also here.
It's not possible in any official cross browser way, but if the occasional false positive is acceptable, you can check for a window.onresize event. Users resizing their windows after loading a page is somewhat uncommon. It's even more effective if you expect users will be frequently opening the console, meaning less false positives as a percentage.
window.onresize = function(){
if ((window.outerHeight - window.innerHeight) > 100) {
// console was opened (or screen was resized)
}
}
Credit to https://stackoverflow.com/a/7809413/3774582. Although that question is chrome specific, the concept applies here.
To expand on this, if you need a very low tolerance on false positives, most window resizes will trigger this event dozens of times because it is usually done as a drag action, while opening the console will only trigger this once. If you can detect this, the approach will become even more accurate.
Note: This will fail to detect if the console is already open when the user visits the page, or if the user opens the console in a new window.
(function() {
'use strict';
const el = new Image();
let consoleIsOpen = false;
let consoleOpened = false;
Object.defineProperty(el, 'id', {
get: () => {
consoleIsOpen = true;
}
});
const verify = () => {
console.dir(el);
if (consoleIsOpen === false && consoleOpened === true) {
// console closed
window.dispatchEvent(new Event('devtools-opened'));
consoleOpened = false;
} else if (consoleIsOpen === true && consoleOpened === false) {
// console opened
window.dispatchEvent(new Event('devtools-closed'));
consoleOpened = true;
}
consoleIsOpen = false;
setTimeout(verify, 1000);
}
verify();
})();
window.addEventListener('devtools-opened', ()=>{console.log('opened')});
window.addEventListener('devtools-closed', ()=>{console.log('closed')});
Here is a code that worked for me.
This solution works like a charm
https://github.com/sindresorhus/devtools-detect
if you are not using modules - disable lines
// if (typeof module !== 'undefined' && module.exports) {
// module.exports = devtools;
// } else {
window.devtools = devtools;
// }
and result is then here
window.devtools.isOpen
I for my project use the blur event.
function yourFunction() {}
window.addEventListener('blur',(e)=>{e.preventDefault(); yourFunction()})
This will execute yourFunction when the window loses focus.
For instance when someone opens the DevTools.
Okay seems like it also fires when you try to access a different window... so maybe not the best solution.
Maybe pair it with looking at the width of the browser.
If it chainged you can be pretty sure about it I think

visibilitychange event is not triggered when switching program/window with ALT+TAB or clicking in taskbar

The problem is with the behaviour of the event "visibilitychange".
It's triggered:
- When I switch to a different tab inside the browser window.
When I click in minimize / restore buttons for the browser window.
(this is ok)
It's not triggered:
- When I switch to a different window/program using ALT+TAB.
When I switch to a different window/program clicking on taskbar.
(this SHOULD trigger, because, just like when minimizing, the window's visibility may change)
W3 Page Visibility API Documentation: http://www.w3.org/TR/page-visibility/
There is no definition of "page visibility" regarding ALT+TAB/program switching in the spec sheet. I'm guessing it has something to do in between the OS and the Browser.
TESTED IN
Browsers:
Chrome 40.0.2214.115 m / Firefox 36.0.1 / Internet Explorer 11.0.9600.17107
OS: Windows 8.1
Is there a workaround to fix this behaviour? The implementation is fairly simple, I listen to the "visibilitychange" event using jQuery, and then in its callback, I check for the value of "document.visibilityState", but the problem is that the event is not firing when expected.
$(document).on('visibilitychange', function() {
if(document.visibilityState == 'hidden') {
// page is hidden
} else {
// page is visible
}
});
This can be done without jQuery too, but the ALT+TAB and taskbar switch hide/show expected behaviour is still missing:
if(document.addEventListener){
document.addEventListener("visibilitychange", function() {
// check for page visibility
});
}
I've also tried the ifvisible.js module (https://github.com/serkanyersen/ifvisible.js) but the behaviour is the same.
ifvisible.on('blur', function() {
// page is hidden
});
ifvisible.on('focus', function() {
// page is visible
});
I haven't tested in other browsers because if I can't make it work in Chrome on Windows I really don't care about the other browsers yet.
Any help or suggestions?
UPDATE
I tried using different vendor prefixes for the event name (visibilitychange, webkitvisibilitychange, mozvisibilitychange, msvisibilitychange) but but still the event is not triggered when I switch to a different program in the taskbar or ALT+TAB, or even if I open the start menu thing in windows with the windows key, which covers the whole screen.
I can reproduce the exact same issue in Chrome, Firefox and Internet Explorer.
UPDATE #2
Here's a roundup post I wrote for this issue and a workaround in pure Javascript to solve the encountered problems.
UPDATE #3
Edited to include a copy of the sourced blog post. (see accepted answer)
Here's a roundup post I wrote for this issue and a workaround in pure JavaScript to solve the encountered problems.
Edited to include a copy of the sourced blog post:
In any kind of javascript application we develop there may be a
feature or any change in the application which reacts according to the
current user visibility state, this could be to pause a playing video
when the user ALT+TABs to a different window, tracking stats about how
the users interact with our application, how often does him switch to
a different tab, how long does it take him to return and a lot of
performance improvements that can benefit from this kind of API.
The Page Visibility API provides us with two top-level attributes:
document.hidden (boolean) and document.visibilityState (which could be
any of these strings: “hidden”, “visible”, “prerender”, “unloaded”).
This would not be not good enough without an event we could listen to
though, that’s why the API also provides the useful visibilitychange
event.
So, here’s a basic example on how we could take action on a visibility
change:
function handleVisibilityChange() {
if(document.hidden) {
// the page is hidden
} else {
// the page is visible
}
}
document.addEventListener("visibilitychange", handleVisibilityChange, false);
We could also check for document.visibilityState value.
Dealing with vendor issues George Berkeley by John Smibert
Some of the implementations on some browsers still need that the
attributes or even the event name is vendor-prefixed, this means we
may need to listen to the msvisibilitychange event or check for the
document.webkitHidden or the document.mozHidden attributes. In order
to do so, we should check if any vendor-prefixed attribute is set, and
once we know which one is the one used in the current browser (only if
there’s the need for a prefix), we can name the event and attributes
properly.
Here’s an example approach on how to handle these prefixes:
var browserPrefixes = ['moz', 'ms', 'o', 'webkit'];
// get the correct attribute name
function getHiddenPropertyName(prefix) {
return (prefix ? prefix + 'Hidden' : 'hidden');
}
// get the correct event name
function getVisibilityEvent(prefix) {
return (prefix ? prefix : '') + 'visibilitychange';
}
// get current browser vendor prefix
function getBrowserPrefix() {
for (var i = 0; i < browserPrefixes.length; i++) {
if(getHiddenPropertyName(browserPrefixes[i]) in document) {
// return vendor prefix
return browserPrefixes[i];
}
}
// no vendor prefix needed
return null;
}
// bind and handle events
var browserPrefix = getBrowserPrefix();
function handleVisibilityChange() {
if(document[getHiddenPropertyName(browserPrefix )]) {
// the page is hidden
console.log('hidden');
} else {
// the page is visible
console.log('visible');
}
}
document.addEventListener(getVisibilityEvent(browserPrefix), handleVisibilityChange, false);
Other issues There is a challenging issue around the “Page Visibility”
definition: how to determine if the application is visible or not if
the window focus is lost for another window, but not the actual
visibility on the screen? what about different kinds of visibility
lost, like ALT+TAB, WIN/MAC key (start menu / dash), taskbar/dock
actions, WIN+L (lock screen), window minimize, window close, tab
switching. What about the behaviour on mobile devices?
There’s lots of ways in which we may lose or gain visibility and a lot
of possible interactions between the browser and the OS, therefore I
don’t think there’s a proper and complete “visible page” definition in
the W3C spec. This is the definition we get for the document.hidden
attribute:
HIDDEN ATTRIBUTE On getting, the hidden attribute MUST return true if
the Document contained by the top level browsing context (root window
in the browser’s viewport) [HTML5] is not visible at all. The
attribute MUST return false if the Document contained by the top level
browsing context is at least partially visible on at least one screen.
If the defaultView of the Document is null, on getting, the hidden
attribute MUST return true.
To accommodate accessibility tools that are typically full screen but
still show a view of the page, when applicable, this attribute MAY
return false when the User Agent is not minimized but is fully
obscured by other applications.
I’ve found several inconsistencies on when the event is actually
fired, for example (Chrome 41.0.2272.101 m, on Windows 8.1) the event
is not fired when I ALT+TAB to a different window/program nor when I
ALT+TAB again to return, but it IS fired if I CTRL+TAB and then
CTRL+SHIFT+TAB to switch between browser tabs. It’s also fired when I
click on the minimize button, but it’s not fired if the window is not
maximized and I click my editor window which is behing the browser
window. So the behaviour of this API and it’s different
implementations are still obscure.
A workaround for this, is to compensate taking advantage of the better
implemented focus and blur events, and making a custom approach to the
whole “Page Visibility” issue using an internal flag to prevent
multiple executions, this is what I’ve come up with:
var browserPrefixes = ['moz', 'ms', 'o', 'webkit'],
isVisible = true; // internal flag, defaults to true
// get the correct attribute name
function getHiddenPropertyName(prefix) {
return (prefix ? prefix + 'Hidden' : 'hidden');
}
// get the correct event name
function getVisibilityEvent(prefix) {
return (prefix ? prefix : '') + 'visibilitychange';
}
// get current browser vendor prefix
function getBrowserPrefix() {
for (var i = 0; i < browserPrefixes.length; i++) {
if(getHiddenPropertyName(browserPrefixes[i]) in document) {
// return vendor prefix
return browserPrefixes[i];
}
}
// no vendor prefix needed
return null;
}
// bind and handle events
var browserPrefix = getBrowserPrefix(),
hiddenPropertyName = getHiddenPropertyName(browserPrefix),
visibilityEventName = getVisibilityEvent(browserPrefix);
function onVisible() {
// prevent double execution
if(isVisible) {
return;
}
// change flag value
isVisible = true;
console.log('visible}
function onHidden() {
// prevent double execution
if(!isVisible) {
return;
}
// change flag value
isVisible = false;
console.log('hidden}
function handleVisibilityChange(forcedFlag) {
// forcedFlag is a boolean when this event handler is triggered by a
// focus or blur eventotherwise it's an Event object
if(typeof forcedFlag === "boolean") {
if(forcedFlag) {
return onVisible();
}
return onHidden();
}
if(document[hiddenPropertyName]) {
return onHidden();
}
return onVisible();
}
document.addEventListener(visibilityEventName, handleVisibilityChange, false);
// extra event listeners for better behaviour
document.addEventListener('focus', function() {
handleVisibilityChange(true);
}, false);
document.addEventListener('blur', function() {
handleVisibilityChange(false);
}, false);
window.addEventListener('focus', function() {
handleVisibilityChange(true);
}, false);
window.addEventListener('blur', function() {
handleVisibilityChange(false);
}, false);
I welcome any feedback on this workaround. Some other great sources
for ideas on this subject:
Using the Page Visibility API Using PC Hardware more efficiently in
HTML5: New Web Performance APIs, Part 2 Introduction to the Page
Visibility API Conclusion The technologies of the web are continuously
evolving, we’re still recovering from a dark past where tables where
the markup king, where semantics didn’t mattered, and they weren’t any
standards around how a browser should render a page.
It’s important we push these new standards forward, but sometimes our
development requirements make us still need to adapt to these kind of
transitions, by handling vendor prefixes, testing in different
browsers and differents OSs or depend on third-party tools to properly
identify this differences.
We can only hope for a future where the W3C specifications are
strictly revised, strictly implemented by the browser developer teams,
and maybe one day we will have a common standard for all of us to work
with.
As for the Page Visibility API let’s just kinda cite George Berkeley
and say that:
“being visible” is being perceived.
A working solution is proposed described here: https://stackoverflow.com/a/9502074/698168. It uses a combination of the W3C Page Visibility API, blur/focus and mouse movements. Hidden HTML pages related to Alt+Tab are identified in a probabilistic way (i.e. you cannot determine if your page is hidden with 100% accuracy).
we can do like below when switching between tabs and switching between applications
var pageVisible = true;
function handleVisibilityChange() {
if (document.hidden) {
pageVisible = false;
} else {
pageVisible = true;
}
console.log("handleVisibilityChange")
console.log("pageVisible", pageVisible)
// some function call
}
document.addEventListener("visibilitychange", handleVisibilityChange, false);
window.addEventListener('focus', function() {
pageVisible = true;
// some function call
}, false);
window.addEventListener('blur', function() {
pageVisible = false;
// some function call
}, false);
There's a very simple solution to this I have come across.
You just need to pass false to the useCapture while attaching an event listener to the document. Works like a charm!
document.addEventListener('visibilitychange', function () {
// code goes here
}, false)

Javascript - Script5002 - Function Expected when declaring a variable

I've looked through quite a few answers and other places online, but I haven't found anyone that is experiencing the error in the same way that I am.
My browser just updated to IE10 and that brought this to our attention. If I run in compatibility mode, the function seems to work just fine. If I'm not in compatibility mode, I get an IE debugger error SCRIPT5002 - Function Expected error.
I've marked the place where I get the error with ==>. If I take that variable out and replace the variable with the document.frames... it then references that line as the problem. Any help would be appreciated.
I inherited this code from a previous employee and have only been working with javascript for about 3 months. Here is the code:
function FncSaveClient(){
//Submit Primary Client form
//Verify Data
==> var CntSumFrm = document.frames('IFrameSummary').document.all.item('DefaultFrm');
if (CntSumFrm.fireEvent('onsubmit') == true){
CntSumFrm.submit();
}
//If Edit Mode Submit Subforms
var IntAcctNum = CntSumFrm.TxtAcctNum.value
if (IntAcctNum != 0){
//Locations Subform
var CntLocFrm = document.frames('IFrameLocations').document.all.item('DefaultFrm');
if (CntLocFrm.fireEvent('onsubmit') == true){
CntLocFrm.submit();
}
//Contacts Subform
var CntContactTbl = document.frames('IFrameContacts').document.all.item('TblContactSummary')
if (CntContactTbl.rows.length-3 == 0){
alert('You must have at least one contact per client.');
document.all.item('BtnSubTblClientContacts').style.color='red';
}
//Classification Subform
var CntClassFrm = document.frames('IFrameMarketing').document.frames('IFrameClassification').document.all.item('DefaultFrm');
if (CntClassFrm.fireEvent('onsubmit') == true){
CntClassFrm.submit();
}
//Save Client Admin
var CntAdminFrm = document.frames('IFrameAdmin').document.all.item('DefaultFrm');
if (CntAdminFrm.fireEvent('onsubmit') == true){
CntAdminFrm.submit();
}
else
{
document.all.item('BtnSubTblSalesRel').style.color='red';
}
}
if(CntSumFrm.TxtDeleted.value == 1)
{
window.parent.location.href = '/Accounts/';
}
}
That code is full of ancient IE-specific code, that is probably not allowed anymore even by IE, unless in compatibility mode. You should look into replacing stuff like:
document.frames
document.all
.items()
I believe the error happens because frames or item (maybe both) is not a function when IE follows the JS standards.
I had a similar issue with a Java Script I wrote back in 2005 today. An external user using IE10, which we are still back in IE8, couldn't get things to work properly. It appears that document.all has been deprecated and is only accessibly in compatibility mode. I removed the check I had for IE and so it now uses document.getElementById which I already had for other browsers, and it appears to work even with compatibility mode turned off.

How to identify buggy behavior in "input" event without browser detection?

I'll start with the question. When a specific browser has a buggy implementation of a feature and your javascript needs to know whether the current browser has that buggy implementation or not so it can use an alternate strategy, how do you figure out if the implementation is buggy without doing browser type sniffing (which is generally considered bad)?
Here's the whole situation.
I was working on some code that wants to use the "input" event for getting notifications of user changes to an <input type="text"> field (works much more live than the "change" event), but when that event isn't supported, it uses a much more complicated scheme involving a bunch of other events.
Since the "input" event is only supported in some browsers, I went in search of a way to do feature detection for the event (rather than browser user agent sniffing) since feature detection is generally a more robust way of doing things. As such, I came across this great article for doing exactly that and this code seems to work:
var isEventSupported = (function(){
var TAGNAMES = {
'select':'input','change':'input',
'submit':'form','reset':'form',
'error':'img','load':'img','abort':'img'
}
function isEventSupported(eventName) {
var el = document.createElement(TAGNAMES[eventName] || 'div');
eventName = 'on' + eventName;
var isSupported = (eventName in el);
if (!isSupported) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] == 'function';
}
el = null;
return isSupported;
}
return isEventSupported;
})();
Then, I ran into problems with IE (surprise, surprise). While IE purports to support the "input" event and it passes the feature test above and it works most of the time, IE's support is buggy as hell. It doesn't even trigger the event when the user hits the backspace key (among other missing behaviors). As such, I can't rely on it in IE. So, I had built this nice clean code that did a feature test for the "input" event and uses it's very clean implementation when present and when not present used this much uglier work-around involving monitoring eight other events. Now, it's busted in IE because the feature test for the "input" event passes so the code attempts to use it, but it's buggy as hell so it doesn't work.
Since these IE bugs show up on user actions, I can't think of any way to devise a javascript feature test to identify the buggy behavior. As such, my only current path is to resort to browser sniffing and refuse to rely on the "input" tag if the browser is IE.
Are there any options here for identifying the buggy behavior in the "input" event besides browser sniffing? If one had to do browser sniffing, is there a way to identify IE by behavior rather than a user agent string that can be freely spoofed and isn't guaranteed to be accurate?
jamie-pate suggest something like this:
var broken = false,
ta = angular.element('<textarea>').on('input', function(evt) {
broken = true;
});
ta.attr('placeholder', 'IESUCKS');
So you can check for "supports input event and is not 'broken'" in your code.
See https://github.com/angular/angular.js/issues/2614?source=c
If you are interested in a cross-browser "input change" event, here is my implementation:
function onInputChange(domInput, callback) {
if (domInput.addEventListener) {
domInput.addEventListener('input', callback, false); // Firefox, etc.
} else if (domInput.attachEvent) {
domInput.attachEvent('onpropertychange', callback); // IE
}
}
Usage example:
var leInput = document.getElementById('myInput');
var leCallback = function () {
// awesome stuff here
};
onInputChange(leInput, leCallback);
Works in all browsers, supports keyboard input and copy/paste.
However there is the exception of that cursed IE9, which didn't exist at the time I wrote the above code. Would Microsoft ever consider fixing their bug? :\

Javascript request fullscreen is unreliable

I'm trying to use the JavaScript FullScreen API, using workarounds for current non-standard implementations from here:
https://developer.mozilla.org/en/DOM/Using_full-screen_mode#AutoCompatibilityTable
Sadly, it behaves very erratically. I only care about Chrome (using v17), but since I was having problems I did some tests in Firefox 10 for comparison, results are similar.
The code below attempts to set the browser to fullscreen, sometimes it works, sometimes not. It ALWAYS calls the alert to indicate it is requesting fullscreen. Here's what I've found:
It USUALLY sets fullscreen. It can get to a state where this stops working, but the alert still happens, i.e. it is still requesting FullScreen, but it doesn't work.
It can work if called from a keypress handler (document.onkeypress), but not when called on page loading (window.onload).
My code is as follows:
function DoFullScreen() {
var isInFullScreen = (document.fullScreenElement && document.fullScreenElement !== null) || // alternative standard method
(document.mozFullScreen || document.webkitIsFullScreen);
var docElm = document.documentElement;
if (!isInFullScreen) {
if (docElm.requestFullscreen) {
docElm.requestFullscreen();
}
else if (docElm.mozRequestFullScreen) {
docElm.mozRequestFullScreen();
alert("Mozilla entering fullscreen!");
}
else if (docElm.webkitRequestFullScreen) {
docElm.webkitRequestFullScreen();
alert("Webkit entering fullscreen!");
}
}
}
requestFullscreen() can not be called automatically is because of security reasons (at least in Chrome). Therefore it can only be called by a user action such as:
click (button, link...)
key (keydown, keypress...)
And if your document is contained in a frame:
allowfullscreen needs to be present on the <iframe> element*
* W3 Spec:
"...To prevent embedded content from going fullscreen only embedded content specifically allowed via the allowfullscreen attribute of the HTML iframe element will be able to go fullscreen. This prevents untrusted content from going fullscreen..."
Read more: W3 Spec on Fullscreen
Also mentioned by #abergmeier, on Firefox your fullscreen request must be executed within 1 second after the user-generated event was fired.
I know this is quite an old question but it is still the top result in Google when searching for FireFox's error message when calling mozRequestFullScreen() from code that wasn't triggered by any user interaction.
Request for full-screen was denied because
Element.mozRequestFullScreen() was not called from inside a short
running user-generated event handler.
As already discussed this is a security setting and therefore is the correct behaviour in normal browser environment (end user machine).
But I am writting an HTML5-based digital signage application which runs under a controlled environment without any user interaction intended. It is vital for my apllication to be able to switch to fullscreen automatically.
Luckily FireFox offers a possibilty to remove this restriction on the browser, which is rather hard to find. I will write it here as future reference for everybody finding this page via the Google search as I did
On the about:config page search for the following key and set it to false
full-screen-api.allow-trusted-requests-only
For my digital signage application I also removed the prompt the browser shows when entering fullscren:
full-screen-api.approval-required
Hopefully this might save someone the hours I wasted to find these settings.
You have nothing wrong with your function. In Firefox, if you call that function directly, it will prevent to for full-screen. As you know, Request for full-screen was denied because docElm.mozRequestFullScreen(); was not called from inside a short running user-generated event handler. So, You have to call the function on event such as onClick in Firefox.
Full Screen Mode
Another unexpected issue with requestFullscreen() is that parent frames need to have the allowfullscreen attribute, otherwise Firefox outputs the following error:
Request for fullscreen was denied because at least one of the document’s containing elements is not an iframe or does not have an “allowfullscreen” attribute.
Aside from iframes, this can be caused by your page being within a frameset frame. Because frameset is deprecated, there is no support for the HTML5 allowfullscreen attribute, and the requestFullscreen() call fails.
The Firefox documentation explicitly states this on MDN, but I think it bears reiterating here, for developers who might not read the documentation first.... ahem
Only elements in the top-level document or in an with the allowfullscreen attribute can be displayed full-screen. This means that elements inside a frame or an object can't.
I realize this is an old post, but in case someone else finds this I'd like to add a few suggestions and sample code.
To help avoid this error...
Failed to execute 'requestFullscreen' on 'Element': API can only be
initiated by a user gesture.
Don't test for the existence of requestFullscreen(), which is a method. Instead, test for the existence of a property like document.fullscreenEnabled.
Also consider the following...
Move your fullscreen check into its own function so you can reuse it.
Make DoFullScreen() reusable by passing the element you want to affect as a parameter.
Use a guard clause at the top of DoFullScreen() to exit out of the function immediately if the window is already in fullscreen mode. This also simplifies the logic.
Set a default value for your DoFullScreen() element parameter to ensure the requestFullscreen() method is always called on an existing element. Defaulting to document.documentElement will probably save you some keystrokes.
// Move your fullscreen check into its own function
function isFullScreen() {
return Boolean(
document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement
);
}
// Make DoFullScreen() reusable by passing the element as a parameter
function DoFullScreen(el) {
// Use a guard clause to exit out of the function immediately
if (isFullScreen()) return false;
// Set a default value for your element parameter
if (el === undefined) el = document.documentElement;
// Test for the existence of document.fullscreenEnabled instead of requestFullscreen()
if (document.fullscreenEnabled) {
el.requestFullscreen();
} else if (document.webkitFullscreenEnabled) {
el.webkitRequestFullscreen();
} else if (document.mozFullScreenEnabled) {
el.mozRequestFullScreen();
} else if (document.msFullscreenEnabled) {
el.msRequestFullscreen();
}
}
(function () {
const btnFullscreenContent = document.querySelector(".request-fullscreen-content");
const el = document.querySelector(".fullscreen-content");
// Request the .fullscreen-content element go into fullscreen mode
btnFullscreenContent .addEventListener("click", function (){ DoFullScreen(el) }, false);
const btnFullscreenDocument = document.querySelector(".request-fullscreen-document");
// Request the document.documentElement go into fullscreen mode by not passing element
btnFullscreenDocument .addEventListener("click", function (){ requestFullscreen() }, false);
})();

Categories