Preventing background scrolling while using a fixed overlay in jQuery/CSS

I'm working on an overlay box that is fixed and centered on the screen. The page it's being used on is pretty lengthy and has a vertical scrollbar.

My goal is to prevent scrolling of the main page when the overlay is displayed. However, I can't completely disable scrolling because some overlays contain their own vertical scrollbars using overflow-y:scroll. So while the content within the overlay should be scrollable, the main page itself should remain stationary.

Does anyone have any suggestions for how to achieve this using either jQuery or CSS?

Answer №1

If you're looking for a quick and dirty solution, one way to go about it is by adding an event listener to the window for scroll events and using preventDefault() when your overlay is visible.

Here's an example using jQuery:


window.addEventListener('scroll', function(e){
    var el = $('.overlay.active');

    if( el.length > 0 ){
        e.preventDefault();
    }   
});

I hope this meets your requirements.

Answer №2

To prevent scrolling, you have the option to use the CSS property overflow: hidden on the body element. This will keep the main content from scrolling while still allowing child elements to scroll if needed. Check out this sample code snippet in acustomized fiddle.

Answer №3

Enhancing Marc's jQuery solution, my code offers a seamless transition for disabling and re-enabling body scroll when the overlay appears. By simply clicking on the close button or the overlay itself, the body scroll is smoothly re-enabled.

/*Disabling the scroll*/

$(function() {
/*Defining the trigger button to open the overlay*/
$('#overlay1').click(function() {    
/*Specifying the element that will disable the scroll, in this case, the body.*/
    $('body')   
        .css('overflow', 'hidden');
   });

/*Re-enable the scroll*/

/*Designating the elements that will close the overlay, in this case, body and .close*/
$('body, .close').click(function() {
/*Enabling the scroll back on the specified element, which is the body in this instance.*/
    $('body')
        .css('overflow', 'visible');
   });
});

Check out this JSFiddle link to see the script in action.

Answer №4

To ensure your overlay stays fixed on the screen while scrolling, you can use the CSS property {position: fixed;}. This will prevent the overlay from moving along with the page scroll. More information on this can be found here.

Answer №5

To prevent the user from scrolling or interacting with the page, you can design a container that covers the entire width and height of the screen using the CSS property position: fixed. Within this container, you can place your overlay containing the necessary information for the user.

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

jQuery ensures that the show and hide features happen instantly

I have a single div containing two other div elements: <div> <div id="card-container">....</div> <div id="wait-for-result-container" style="display: none;">...</div> </div> When a specific event occurs, I want to swi ...

Using JavaScript to switch the classes of buttons and elements

Hey there! I received this code from a friend who was trying to modify the switch buttons. I made some changes so that each button can now change the state of two separate elements when pressed. Here's the altered code: function toggleClass(ev){ v ...

When attempting to utilize vue-resource, I encountered the error message: "Uncaught TypeError: window.Vue.use is not defined."

As a newcomer to Vue.js, I recently attempted to incorporate vue-resource into my project only to encounter the following error: Uncaught TypeError: window.Vue.use is not a function at vue-resource.js:1469 at vue-resource.js:10 at vue-resource.js: ...

Exploring the depths of HTML 5, harnessing the power of

As I embark on a new website project, I am excited to incorporate HTML5 for a fresh and dynamic look. To address potential compatibility issues with Internet Explorer, I have decided to utilize the resources provided by the HTML5 Boilerplate project. In m ...

The nested navigation link disappears suddenly on Internet Explorer 9

This query closely resembles another issue: Nested menu keeps vanishing on IE 8 & 9. However, the solution provided is quite limited. Why do my nested menus disappear before I can reach them with my cursor unless I move it swiftly? This peculiar behavi ...

Highlighting neighboring components with the same marker when hovering in Slate JS: a step-by-step guide

// custom mouse over hook function useMouseOver() { const [mouseIsOver, setMouseIsOver] = useState(false); return { mouseIsOver, triggers: { onMouseEnter: () => setMouseIsOver(true), onMouseLeave: () => setMouseIsOver(false), ...

Instructions on refreshing a webpage after choosing a sorting option using the onchange attribute

I'm encountering a small issue where the page won't refresh when I select a parameter from a dropdown list. Strangely, when I tested it on a separate document, there was no problem. I suspect Bootstrap may be causing a block somewhere. As someone ...

Use HTML input to enter numbers that are not written in the English language

I am facing an issue with my ASP .Net core web application where I am using Devextreme controls. The main requirement for my application is to support both Persian and Arabic languages, including numbers and dates. I have set up my local windows keyboard ...

The res.render function is failing to render the view and instead, it is generating

When making a call to express/node like this: jQuery.ajax({ url : url, type: "GET", data: {names : names}, success: function(data) { console.log("ajax post success"); }, ...

What issue is present with this AJAX query?

Can you help me figure out where I went wrong with this AJAX code example that I'm trying to learn from? function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new ...

Retrieve the output of a function that was invoked by the getJSON method

In the scenario where $.getJSON() successfully retrieves JSON data, a designated function is executed. Is there a way for me to capture the value returned by this function as output? $.getJSON(url, function(data) { // Perform operations with data u ...

The collapsible section expands upon loading the page

Trying to implement Disqus as a plugin on my test webpage, I created a collapsible section with a "Show comments" button. The idea was to hide the plugin by default and reveal it only when users click on "Show comments". Despite using the w3schools example ...

I am encountering difficulties in utilizing Selenium with Python to access the dropdown menu

Trying to create a Python script using Selenium to automate the registration process for a sample event I have organized. Click here to view the event page. Successfully accessed the page and clicked on the "Join the guestlist" button: from selenium impor ...

"Encountering problem with sending data to server through Ajax

I am facing a very complex issue that requires an in-depth understanding. If this interests you, please continue reading. I have developed a program from scratch that generates an HTML page for user data input and submission. The submitted data is sent to ...

Why is "undefined" being used to alert an ajax call response?

I am encountering an issue with a returned value from an AJAX request. The web method being referenced returns a boolean value of true or false. However, when attempting to access this value outside the AJAX method, I am receiving an "undefined" message :? ...

Retrieve data from backend table only once within the bootstrap modal

How can I retrieve values from a table once a modal is displayed with a form? I am currently unable to access the values from the table behind the modal. Are there any specific rules to follow? What mistake am I making? I would like to extract the values ...

Is an array necessary for updating only the last database record?

Requesting assistance from the PHP and SQL community as I am a novice in these areas. I have successfully created a database and implemented a form on an HTML page to update it. However, I am facing an issue where only the last record is being updated. I s ...

Operating on a duplicate of the array is necessary for mapping an array of objects to function properly

I'm starting to uncover a mysterious aspect of Javascript that has eluded me thus far. Recently, I've been pulling an array of objects from a database using Sequelize. This array is quite intricate, with several associations included. Here' ...

Troubleshooting PHP/MySQL integration with Google Maps - issues persist

I have come across several other posts on this theme but unfortunately, none of them have been able to help me. I am using the article https://developers.google.com/maps/articles/phpsqlajax_v3, however, the code provided is not working for me. I have a fil ...

What is the best way to transfer the JWT token from the server to the client using an HTTP header?

I have been searching for an answer on how to pass the JWT Token from the client to the server securely, but I am not satisfied with the explanations I found. Everyone talks about the most secure way to transfer the JWT token using HTTP headers instead of ...