Cease and Begin Page Overflow / Scroll with a Single Click Feature

Background:
I recently followed a tutorial on how to create a lightbox using HTML, CSS, and JavaScript. However, I encountered an issue where I wanted to disable the scrollbar functionality when the lightbox is displayed, preventing users from scrolling away from the image being viewed. After researching and trying different solutions, I wasn't able to find the right method to achieve this.

I attempted to use the following code snippet:

$(document).css('overflow-y', 'hidden');

Unfortunately, adding this to my code did not have any effect, as if it was never implemented at all.

Question:
Is there a way to prevent page overflow while the lightbox is open and then allow scrolling again when it's closed?

Apologies for any basic oversight, as I'm still new to working with JavaScript.

Javascript:

function startLightBox() {
  var lbBg = document.getElementById("lightBoxBg");
  var lb = document.getElementById("lightBox");
  var screenTop = $(document).scrollTop();
  var currentMid = $(document).scrollTop() + 250;

  $('#lightBoxBg').css('top', screenTop);
  $('#lightBox').css('top', currentMid);

  lbBg.style.display = "block";
  lb.style.display = "block";
}

function dismiss() {
  var lbBg = document.getElementById("lightBoxBg");
  var lb = document.getElementById("lightBox");
  var screenTop = $(document).scrollTop();
  var currentMid = $(document).scrollTop() + 250;


  $('#lightBoxBg').css('top', screenTop);
  $('#lightBox').css('top', currentMid);
  lbBg.style.display = "none";
  lb.style.display = " none";
}

CSS:

#lightBoxBg {
  position: absolute;
  top: 0px;
  left: 0px;
  opacity: 0.5;
  display: none;
  background-color: #000000;
  height: 100%;
  width: 100%;
}

#lightBox {
  position: absolute;
  top: 50%;
  left: 40%;
  display: none;
}

HTML Body

<body>

 // Content here

</body>

Answer №1

Give this a shot-

jquery

Try using

$("body").css("overflow", "hidden");
inside the startLightBox() function.

And add

$("body").css("overflow", "auto");
within the dismiss() function.

Javascript

Implement the following

document.documentElement.style.overflow = 'hidden';  // firefox, chrome
document.body.scroll = "no"; // ie only

in the startLightBox() function.

Then utilize

document.documentElement.style.overflow = 'hidden';  // firefox, chrome
document.body.scroll = "no"; // ie only

inside the dismiss() function.

Answer №2

To modify the overflow for the selector html, body, you must adjust it there as you cannot directly control the CSS of document since it is not an element.

Below is a sample code snippet to demonstrate this:

var toggled = false;
$('.visible').on('click', 'button', function() {
  toggled = !toggled;
  $(this).text((toggled ? 'Enable' : 'Disable') + ' scrolling');
  $('body, html').css('overflow', toggled ? 'hidden' : '');
});
body {
  background-image: linear-gradient(to bottom, white, black);
  height: 140vh;
  position: relative;
}

.visible, .invisible {
  position: absolute;
  color: red;
}

.visible {
  top: calc(100vh - 2rem);
}

.invisible {
  top: calc(140vh - 2rem);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="visible">Visible <button>Disable scrolling</button></div>
<div class="invisible">Invisible</div>

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

Interconnected HTML div values impacting one another

Forgive me for the not-so-great title, as I am unsure of what this particular HTML coding method is called. That's why I am asking this question in the first place. I've written some code and I need to know what type of coding practice this is. ...

Error encountered: The middleware being used is not recognized as a function within the Reddit-clone application. This issue arises while fetching data from

I've been troubleshooting my Reddit-inspired app, and I'm struggling to overcome this issue. I've attempted solutions suggested in YouTube tutorials and followed the documentation for this specific issue. My app is built using Redux-Toolkit. ...

Eliminate all key-value pairs from an array of objects except for the specified key-value pair

I've got an array filled with objects const myArr = [ {k1: 1, k2: 1, k3: 3, k4: 4}, {k1: 1, k2: 2, k3: 3, k4: 4}, {k1: 1, k2: 2, k3: 3, k4: 4}, {k1: 1, k2: 2, k3: 3, k4: 4} ] I'm attempting to filter these objects, although I don&apos ...

Ways to change the chart type in ApexCharts

I'm seeking a way to change the chart type of an existing ApexCharts that has already been rendered. After reviewing the methods, I attempted to use the updateOptions() method, but encountered the error: Uncaught TypeError: Cannot read property &apos ...

Chrome fails to apply CSS to Polymer 2 web component

The implementation of my web component in Polymer v2 is causing a styling issue specifically in Google Chrome. Despite including a CSS file that defines a style called n-action-button, the styling is not being applied to the content of the web component in ...

Troubles encountered with jQuery validate plugin in ASP.NET controls functionality

I'm having trouble using the jQuery plugin validate() method to validate a div within my current SharePoint Visual WebPart. I can't figure out why it's not working at all. Here is the code: <div id="main" runat="server"> ...

What could be the reason that the accordion is failing to expand or collapse when clicked?

I am facing an issue where the div is not expanding or collapsing upon clicking the + sign. I have tried removing unnecessary scripts but it still doesn't work. Additionally, there is an error in the console: Uncaught TypeError: $(...).slideReveal is ...

How to Enhance GraphQL Mutation OutputFields with a Function Generator

I'm encountering issues while trying to incorporate a function generator within a GraphQL mutation. The function generator is utilized to streamline the promise chain inside the mutation. Prior to refactoring the code, everything was functioning corr ...

A guide to fetching web results using YQL with JavaScript

I've been attempting to implement the code provided in How to use YQL to retrieve web results? Unfortunately, it's not functioning as expected. If you have any alternative suggestions or can help rectify the code, please let me know. I'm ...

What is the best way to transform a GET request with a query string into a promise?

After successfully making a request with querystring params, I encountered an issue while trying to promisify my request: // Works var Promise = require("bluebird"); var request = Promise.promisifyAll(require("request")); request.get({ url: 'htt ...

Arranging and structuring Handlebars templates

In this particular example... http://example.com/1 ...I am experimenting with organizing a Handlebars template and its corresponding content in separate files, as opposed to having them all combined in the HTML file or JavaScript script, like in this con ...

Exploring the functionality of promises in JavaScript

Currently, I am using the most recent version of Angular. The code snippet I've written looks like this: $q.all({ a: $q.then(func1, failHandler), b: $q.then(func2, failHandler), c: $q.then(func3, failHandler), }).then(func4); Is it guaranteed ...

Tips for preloading icon font in Angular server-side rendering (SSR)

Is it possible to preload icons and fonts before the HTML content is rendered? I have been using a preload strategy to try and achieve this. index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8&quo ...

What steps can be taken to ensure that the array of identifier tags for each student remains intact even after being re-fetched from the API

I am facing an issue where my list of students displayed on the web browser resets when filter fields are cleared. The students are fetched from an API and displayed based on name/tag filters. But, after clearing the filters, the tags associated with each ...

The compatibility issues with the textarea and text-indent: placeholder feature on EDGE are causing functionality problems

I'm facing a peculiar problem with placeholders when using the Edge browser. In my current project, I need to implement a textarea with a specific text-indent property. However, on Edge, the placeholder text appears displaced more than expected. To h ...

CSS not being applied properly in Devise(Rails) emails when sent to Gmail addresses

Upon a user signing up, I send a confirmation email using Devise's mailer view. While everything else appears to be functioning properly, the CSS for CONFIRM ACCOUNT doesn't seem to be applied at all. I've read that CSS classes cannot be use ...

Encounter issue when using GAS withSuccessHandler function

I've developed a Google Sheets add-on that utilizes a modal dialog for the user interface. I encountered an issue with the success handler not running as expected, so I created a basic test interface to troubleshoot the problem. After the server-side ...

Is the presence of a potential leak suggested by this arrangement in the heap snapshot retainer hierarchy

While analyzing a Heap snapshot, I came across a retainer hierarchy that looks like this: https://i.sstatic.net/Zg3bJ.png Is it possible that the MuiThemeProviderOld element (highlighted in yellow and from the @material-ui/core library) is causing a memo ...

HTML slider overlaps fixed buttons

I have a fixed button on my HTML site that redirects to another link. It appears correctly on most pages, but overlaps with the slider on my index page. $(document).ready(function(){ // hide #back-top first //$(".back-top").hide(); // fade in # ...

What is the process for incorporating a personalized SVG file into the material-ui Icon Component?

For my project, I have a requirement to use custom svg files. To achieve this, I am utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0865697c6d7a616964257d61483b2631263b">[email protected]</a>. I reviewed ...