Display the page scrollbar exclusively when in full-screen mode

Here is the JavaScript code that can make a webpage go fullscreen upon clicking a link:

<a href="javascript:void(0)" onclick="javascript:toggleFullScreen()"></a>

// mozfullscreenerror event handler
function errorHandler() {
   alert('mozfullscreenerror');
}
document.documentElement.addEventListener('mozfullscreenerror', errorHandler, false);

// toggle full screen
function toggleFullScreen() {
  if (!document.fullscreenElement &&    // alternative standard method
      !document.mozFullScreenElement && !document.webkitFullscreenElement) {  // current working methods
    if (document.documentElement.requestFullscreen) {
      document.documentElement.requestFullscreen();
    } else if (document.documentElement.mozRequestFullScreen) {
      document.documentElement.mozRequestFullScreen();
    } else if (document.documentElement.webkitRequestFullscreen) {
      document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
    }
  } else {
    if (document.cancelFullScreen) {
      document.cancelFullScreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitCancelFullScreen) {
      document.webkitCancelFullScreen();
    }
  }
}

// keydown event handler
document.addEventListener('keydown', function(e) {
  if (e.keyCode == 13 || e.keyCode == 70) { // F or Enter key
    toggleFullScreen();
  }
}, false);

Is there a way to show scroll overflow only when in fullscreen mode and hide it when the user exits fullscreen either by clicking the same link again or by another method?

Answer №1

To manage overflow, you can create a 'no overflow' class and incorporate it into your function like this:

if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) {  
        document.body.className = document.body.className.replace(' no-scroll', '');
        ...
} else {
    document.body.className += " no-scroll";

Check out this example for toggling the scroll on and off using the method above.

// Add or remove 'no-scroll' class from body
function toggleNoScroll(off) {
    //  Check if class already exists:
    var a = Array.prototype.indexOf.call(document.body.classList, 'no-scroll') + 1;
    //  Remove the class if it exists to prevent duplication
    document.body.className = document.body.className.replace(' no-scroll', '');
    //  Add the class only if off is false or not true && it didn't exist previously (toggling behavior)
    if (off === false || (off !== true && !a)) {
        document.body.className += " no-scroll";
    }
    return document.body.classList;
}

You can now use the function as follows:

if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) {
    toggleNoScroll(true);
...
else {
    toggleNoScroll(false);

Answer №2

To apply a class to your body tag when executing the toggleFullscreen() function, use the following code snippet:

document.body.classList.add('fullScreened')

Next, include a CSS rule like this:

.fullScreened { display: none; }

Please inform me of the outcome once you have tested it out! :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the directive manually replaces the element's content, ngRepeat fails to remove the old entries

I created a directive that utilizes different templates based on the state of the scope as shown below: app.directive('foo', function($compile) { return { restrict: 'E', scope: { bar: '=' }, link: func ...

End the child process.execution after a specific amount of time

I have been searching for information on child process waiting time or response waiting time, but I haven't found anything useful. I'm in need of something like that, so I hope someone can assist me. When I look at the code below, I am printing ...

What is the issue with this jQuery variable?

As a newcomer to Jquery, I am striving to improve my skills. I've been struggling with a variable issue and have spent hours searching the web for a solution without success. $(document).ready(function() { $("a").click(function(){ var l ...

Tips on specifying the behavior of an instantiated function in JavaScript

When using ES2015, my goal is to enhance the Function class and utilize its instance as a callable function. class Foo extends Function { // What is the best way to implement behavior here? } let foo = new Foo(); foo(); foo.call(); // The object is ca ...

Expansive Child Division with Ample Margins

I'm currently working with a nested set of divs and I need the inner div to occupy the full width without extending beyond the parent div's margins. Despite trying to use max-width:100%, it hasn't been successful so far. For this particular ...

Display data in Highchart legend only if it has values

In a unique scenario, I am required to compare various items and display the results in a chart. The user inputs two, three, or four article IDs and receives the corresponding data displayed in a chart. The issue arises when the user enters only two or th ...

jQuery has a problem with the $.each method

I've created a function that checks elements with the class name .sitem. If any of these elements have a blank value, it should return an error message. Otherwise, the code should proceed as normal. if($(".sitem").each(function(ss, element) { if($(t ...

Tips for replacing the nested array object in JavaScript

I am seeking guidance on how to merge and overwrite the existing object values in a nested array using JavaScript. In the scenario presented below, I want to merge the 'other_obj' with the 'obj' that has an id of "zen", overwriting the ...

What are the steps to utilize a public or internal class in JavaScript within an Asp.Net environment?

I've been developing an asp.net web application and I'm looking to incorporate a class in JavaScript. In the asps.cs file, using a class like this is straightforward: ABC obj = new ABC(); obj.name = "John"; Is it possible to use a class in a si ...

When I open Firefox, all I see is a blank page with only the h2 heading displayed

I am trying to print the text "I can print" on a page, but only the title shows up and the rest of the page is blank. What mistake might I be making? <!DOCTYPE html> <html> <head> <title>Object exercise 4</title> </head& ...

React - issue with modal due to invariant violation

In my application, I have implemented a modal with a dropdown menu containing various Categories. Upon selecting a Category, a new dropdown menu appears which displays Classifications. If a Classification is selected, another component is rendered on the p ...

Uploading and Editing Images Using the DropZone Plugin in Laravel JS

Looking to enhance my project by implementing dropzone for image CRUD operations. I've successfully handled image creation, but struggling with editing existing images. Below is the code snippet where I fetch and upload existing images. Dropzone.autoD ...

Fixing quotation marks for ajax json: Ensuring proper stringification

I have encountered a JSON format like the one below. How can I correct it using JavaScript or perhaps some PHP script? I believe quotation marks should be included around arrays. For example: { "1":[ {"id":"171113524", "title":"xxxx", "category":"4", ...

Click to reveal additional images once the "show more" button is pressed

Hey there! I'm currently working on implementing a feature where, upon clicking "show more", 3 images will be displayed. And if the user clicks again, another set of 3 images will appear, and so on. I seem to be facing some difficulties with the JavaS ...

How to open a PDF file in a new tab using Angular

Within my Angular 12 application, I am seeking to enable users to "view" a PDF file stored locally in the application within a new tab on Google Chrome. Currently, when implementing the code below in HTML, the file downloads rather than opening in a new ta ...

What is the best way to utilize jQuery for submitting a form through ajax and then extracting and interpreting the response?

My code has been simplified to include only the necessary elements for this example. I am able to submit the form successfully, but I am looking to understand how to handle error responses so that I can parse and display them. This is what I have attempte ...

Increase the options available in the dropdown menu by adding more selected items, without removing any already selected

I came across this code on the internet http://jsfiddle.net/bvotcode/owhq5jat/ When I select a new item, the old item is replaced by the new item. How can I add more items without replacing them when I click "dropdown list"? Thank you <select id=&qu ...

Modifying Element Values with JavaScript in Selenium using C#

As a newcomer to automation, I am facing a challenge with automating a web page that has a text field. I initially attempted using driver.FindElement(By.XPath("Xpath of elemnt").SendKeys("Value"); but unfortunately, this method did not work. I then resor ...

I require the variable to be accessible from all corners

Is there a way to access the variable "finalPrice" in a different function? I'm trying to achieve this and could use some guidance. function available(id){ $.ajax({ method:"GET", }).done(function(data){ for( ...

Embrace the D3js Force Layout barrier and dive right in

Currently, I am working on a force layout project. My main objective is to enable the nodes to avoid a particular div element placed in the center without utilizing gravity within the SVG. I have already implemented collision detection and bounding within ...