Lock the vertical scroll of the body without affecting the current scroll position

Recently, I created a modal that hides the scroll bar on the body to allow users to only scroll through the modal content.

The problem arises when I apply overflow-y:hidden - the body scrolls to the top, but I actually want to preserve the page's position.

<body>
    Long content
</body>

scrollY is at 1000

<body style="overflow-y:hidden">
    Long content
</body>

scrollY goes to 0

I've considered saving the current scrollY position and scrolling back once overflow-y is removed. However, this solution doesn't give me the desired effect.

Does anyone have any other suggestions or a better solution?

Answer №1

If you want to ensure the main content of your page is not interacted with until a modal is actioned (closed), one approach could be to wrap your existing content in a div and overlay it with a mask to prevent interactions. Here's an example:

<body>
  <div class='content'>
    Your original content here
  </div>
  <div class="modal-mask">
    <div class="modal">Modal content goes here</div>
  </div>
</body>

By giving the modal mask absolute positioning and covering the entire screen, you can then position your modal where needed on top of it.

Answer №2

Sorry for the delay in response :-D, but I hope this information will be beneficial to someone.

let isLocked = false;
export const addScrollLock = () => {
  if (isLocked) return;

  document.body.style.top = `${window.pageYOffset}px`;
  document.body.classList.add('scroll-lock'); // class with "overflow: hidden" or "position: fixed"
  isLocked = true;
};
export const removeScrollLock = () => {
  const scrolled = parseInt(body.style.top) * -1;

  body.classList.remove('scroll-lock');
  window.scrollTo(0, scrolled);
  isLocked = false;
};

Please remember to call addScrollLock before displaying a new fullscreen popup so that the function can calculate the correct scroll position. Otherwise, you may experience window.pageYOffset = 0 and be scrolled to the top after calling removeScrollLock.

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

What's the best way to dynamically show Bootstrap collapse panels in a loop with AngularJS ng-repeat?

Currently, I am utilizing angularJS and attempting to include a bootstrap collapsible-panel within a loop. The code that I have written is causing all the panel bodies to be displayed beneath the first panel header. I need each body to be shown below i ...

Tips for Sending a Message Using TypeScript Websockets

I'm currently working on an Angular application that requires subscribing to a websocket to receive incoming data. Within the Angular service, I have the following code snippet: setContextChannel(channel) { this.contextWS = new WebSocket(channel ...

What is the best way to save Vue state in a cookie while transitioning between form steps in a Laravel application

Imagine a scenario where a user is filling out a multi-step form, and we want to ensure that their progress is saved in case they lose connection. This way, the user's data will not be lost between different form steps. In addition to saving each ste ...

There are a couple of issues here: specifically, the `this.myMethod` function is not recognized as a function, and the click event added by the `addEventListener` function

I am currently attempting to create a timer using vue.js, but I am encountering some issues with my methods section: methods: { saveRunningMethod() { var runningData = { duration: `${this.hour} : ${this.minute} : ${this.se ...

Secure JSON data by transmitting it safely to the front end within a Node.js environment

Currently, I am in the process of building an e-commerce application using NodeJs, Express, and MongoDB. The challenge I am facing is deciding how to securely pass JSON objects from the back end to the front end without compromising data security. Initiall ...

How to Use Express.js to Stream Assets (JS/CSS/images) from Amazon S3

After successfully launching my Node.js blog on AppFog, I have the idea of utilizing an Amazon S3 bucket to host and stream all my assets such as javascript, stylesheets, and images. I am now wondering how I can configure Express.js to properly serve thes ...

Guide to aligning text vertically in a column alongside an image using Bootstrap 5

I have been using the Bootstrap 5.3.2 grid system for most of my website. I am trying to create a layout with an image on the left and text on the right. However, I am facing an issue with aligning the text vertically in the column. Is there a way to achie ...

PHP does not properly interpret quotation marks when passed from an HTML form

My current setup involves a simple HTML form with a submit button that triggers my PHP script to process the input. However, I've encountered an issue where my PHP code fails to recognize the quotation mark when using str_replace function. Below is a ...

Executing a series of tests using Postman

Is running multiple requests in a postman script feasible? I have an endpoint: http://localhost/gadgets/{id}/buy This endpoint sets a flag in a gadget object/entry based on its id. With hundreds of gadgets, can I use a shared file of ids to create and run ...

Experiencing unexpected behavior with React Redux in combination with Next.js and NodeJS

I'm in the process of developing an application using Next.js along with redux by utilizing this particular example. Below is a snippet from my store.js: // REDUCERS const authReducer = (state = null, action) => { switch (action.type){ ...

What is the best way to invoke my Python function within my JavaScript file?

I am facing an issue with using my Python function in JavaScript. Although the actual code I am working on is more complex, I have simplified it to demonstrate the problem below: main.mjs dbutils.notebook.run("./aPythonFile.py", 5, {"parame ...

Manipulating prop values through dropdown selection

I'm currently working on implementing filtering based on a prop value that changes according to the dropdown selection. Here's my progress so far: template(v-for="field in tableFields") th(:id="field.name") select(@change="filterScope(sc ...

To ensure that checkboxes are automatically checked in AngularJS 1.5, the model should be bound to the objects without using the ng-checked

Due to various conflicts and dependencies, I have opted to use AngularJS 1.5.x instead of 1.6.x, which has led me to encounter some issues with ng-checked functionality. Within my ng-repeat loop, I am dealing with 2 objects: vm.stateList, containing all ...

What's the best way to prevent extra spacing when typing in a materialUI TextField?

Instructions for the user: Please input your first name without any spaces between characters. I attempted to implement the following code, however, it did not achieve the desired outcome. <TextField required id="name" label="First Name" ...

Determine the highest position of itself by using the calculation: 100% viewport height minus y

I'm looking to make an element fill all the space below it until the bottom of the browser window. Is there a way to determine the y offset of the element in order to achieve this? I need help defining y: .occupy-space-below { max-height: calc(10 ...

Head and tail tally

I've been working on coding a heads or tails system in JavaScript, but I've hit a roadblock. I am struggling to find a solution. Here is what I have so far: const userInput = prompt("Heads or Tails?"); const arr = [0, 0, 1, 1, 1, 0, 1, 0, 1]; ...

Tips for transferring form data from controller to connection file

I'm currently working on creating a login page using Angularjs and node.js, but I'm encountering an issue with sending data from the controller to my database connection file for performing transactions. The error message reads: POST http://loca ...

Exploring the functionality of the $.each jQuery iterator. Can someone clarify the distinctions between these two methods?

Having vertices as an array of google.maps.LatLng objects means that they should return latlng points. The first code snippet works perfectly fine, however, I encounter issues when using the second one. // Iterate over the vertices. for (var index =0; ind ...

Utilizing DomQuery in TinyMCE for element retrieval

I'm currently working with TinyMCE to develop a WYSIWYG editor, however, I've encountered an issue that has me feeling stuck. My goal is to establish a system where users can create specific documents, each divided into sections as wrappers. Wit ...

Cache HTML files in Python

I need to clean up some locally saved HTML files by removing unnecessary information such as <script> and <style> tags along with their content. I am using Selenium web browser to access the page source like so: from selenium import webdriver ...