Stop background scrolling with CSS overlay menu

Is there a way to create a CSS overlay menu that prevents the main content it covers from scrolling when the menu is active? In other words, I want users to be able to scroll through the menu without affecting the background content.

I've managed to create a menu overlay, but whenever someone scrolls through it, the background content also scrolls. Is there a way to freeze the background when the menu is open?

Below is the JavaScript code I used for the menu:

// Function to display menu overlay and hide background content
function openNav() {
    document.querySelector("nav").style.display = "block";
    document.querySelector("body").style.background = "#999";
    document.getElementById("btn-menuclose").style.display = "block";
    document.getElementById("btn-menu").style.display = "none";
    document.getElementById("background").style.display = "none";  
}

// Function to close menu overlay and reveal background content again
function closeNav() {
    document.querySelector("nav").style.display = "none";
    document.querySelector("body").style.background = "#fff";
    document.getElementById("btn-menuclose").style.display = "none";
    document.getElementById("btn-menu").style.display = "block";
    document.getElementById("background").style.display = "block";  
}

Answer №1

Ensure that the body has overflow:none applied when the overflow is set to visible.

// Function to show menu overlay and hide background content   
function openNav() {
document.querySelector("nav").style.display = "block";
document.querySelector("body").style.background = "#999";
document.getElementById("btn-menuclose").style.display = "block";
document.getElementById("btn-menu").style.display = "none";
document.getElementById("background").style.display = "none"; 
document.querySelector("body").style.overflow ="none";
}

// Function to close menu overlay and reveal background content again
function closeNav() {
document.querySelector('"body".style.overflow = "visible";
document.querySelector("body").style.background = "#fff";
document.getElementById("btn-menuclose").style.display = "none";
document.getElementById("btn-menu").style.display = "block";
document.getElementById("background").style.display = "none";  
document.querySelector("nav").style.display = "none";
}

Answer №2

To prevent scrolling, add overflow: hidden; to the specified selector (remember to unset it back to visible later), like this:

// Function to display menu overlay and hide background content   
function openNav() {
document.querySelector("nav").style.display = "block";
document.querySelector("body").style.background = "#999";
document.getElementById("btn-menuclose").style.display = "block";
document.getElementById("btn-menu").style.display = "none";
document.getElementById("background").style.display = "none";  
document.getElementById("background").style.overflow = "hidden";  
}

// Function to close menu overlay and reveal background content again
function closeNav() {
document.querySelector("nav").style.display = "none";
document.querySelector("body").style.background = "#fff";
document.getElementById("btn-menuclose").style.display = "none";
document.getElementById("btn-menu").style.display = "block";
document.getElementById("background").style.display = "none";  
document.getElementById("background").style.overflow = "visible";
}

If needed, you can also directly apply this to the body element.

Answer №3

Dealing with a similar issue recently, I found a reliable solution that met all my needs:

  • Consistency across various devices and screen sizes (iOS Safari being particularly challenging)
  • Fulfilling all requirements (preventing body scroll to top on popup, avoiding strange overscroll, and navigation chrome toggling on iOS Safari)

The answer came in the form of a JavaScript library called body-scroll-lock. While not a pure CSS solution, it perfectly complemented existing JS functions for opening and closing navigation menus.

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

React Full Calendar Error: Unable to access property 'calendar' from undefined

I'm encountering an issue while attempting to save selected time information in state. Any assistance would be greatly appreciated, thank you for your help! Please feel free to ask if more specific details are required. Below is a snippet of code fro ...

Alternative image to be used as background if the default image is not available

I am looking to designate an image as a background, but the image file may be named either bg.png or bg.jpg. Is there a way without using JavaScript to set up a fallback option for an alternate image if the default background image is not available? body ...

transform ajax data into an array structure

I need to convert the values retrieved from an AJAX call into an array so that I can access and format them accordingly. $(document).ready(function() { $('#documenter_nav > li a').click(function(){ var url = $(this).attr('data- ...

Adaptable Bootstrap navigation bar

In the process of creating a responsive menu, I have designed a navbar for desktop that includes 3 text links and 3 small pictures that are also links. However, when transitioning to a smaller screen size, my goal is to keep the 3 small pictures as they a ...

The oninput() event does not trigger on phones and tablets

Currently, I am in the process of developing an application using PhoneGap. An issue has arisen where my code runs perfectly fine when tested on a browser, but the onInput() function does not seem to trigger on mobile devices. <div class="t1">09< ...

I am unable to configure the value using NG-Options

Currently, I am facing an issue with loading a select box using the ng-options directive. The problem is that I am unable to have the options display values ranging from 23-26, instead of 0-3. The values should match the "eigenschap_id" that I pass throug ...

Understanding the source of an useEffect's trigger to create a conditional statement

Within my useEffect, I have two states included in the dependencies array: const [currentTab, setCurrentTab] = useState('open'); const [searchParams, setSearchParams] = useState(''); useEffect(() => { if (condition) { // logi ...

Step-by-step guide on crafting a scrolling marquee with CSS or Javascript

I am in need of creating two marquees for a website project. The first marquee should showcase a repeating image while the second one should display links, both spanning the browser window at any size. It is crucial that the marquee items are displayed fro ...

Having trouble selecting the first td within a tr using CSS3 selectors

I'm encountering an issue with selecting the first td in the tr of a dynamically generated table. I've attempted to do this using: .record_list tbody tr td:first-child { text-align: center; } However, the styles are not being applied as ex ...

Tips for concealing items on a website within a WebView

Is it possible to hide the header element with the search bar and logo when loading this page on a Webview? I'm not familiar with JavaScript, so is there a way to achieve this? The section I am looking to conceal ...

Is it possible to showcase the data from three or more PHP files on a single webpage?

I currently have three PHP files: pie.php, bar.php, and line.php. When each file is run individually, it displays a webpage with a pie chart, bar chart, or line graph respectively. However, running all three files opens up separate webpages for each graph. ...

Determining the scroll position of a JQuery Mobile collapsible set upon expansion

I am utilizing jQueryMobile (v1.4.0) collapsible set / accordions to showcase a list of elements along with their content, which can be seen in this jsFiddle. <div id="List" data-role="collapsible-set"> <div data-role="collapsible" data-conte ...

Firestore generates an error stating that 'onSnapshot() must have 1 to 4 arguments'

I am having trouble retrieving all unread messages for the current user from Firebase. The issue arises when using onSnapshot() as it initially fetches the required data but fails to do so when a new document is added, resulting in an error. FirebaseErro ...

Complete the missing elements of a CSS grid layout

I'm currently working on creating a grid layout that aligns with this wireframe design: https://i.sstatic.net/AdsMX.png Here is the markup I have implemented so far: <div class="grid"> <div class="spanWidth"> <img src="https:// ...

Venom Bot encounters issue with sending files, displaying "Error processing files" message

When attempting to send a PDF in the code snippet below, I encountered the following error: app.post('/send-pdf',[ body('number').notEmpty(), ], async (req, res) => { const errors = validationResult(req).formatWith(({ msg }) =&g ...

There seems to be an issue with the bullet functionality in phaser.io

I'm having trouble firing a bullet from my object in my game. I have been struggling to find the proper reason for the issue. Here is a snippet of my code. Game.js var Game = { preload : function() { // spaceship image screen th ...

JavaScript function not being executed after AJAX response in HTML

There seems to be a problem with my jQuery code. After receiving an html response from an ajax call and prepending it to a div, a div within that received html is not triggering a function in my external javascript file. In the index.php file, I have incl ...

Incorporate a unique identifier for dynamic elements

Is there a way to give generated divs the same name so I can markup them easily? $.getJSON("data/reviews.json", function(data){ for(var i=0; i<data.length; i++) { var review = sym.createChildSymbol("Template", "content"); review.$("title").html ...

It appears that Apexcharts is not compatible with React/Next.js

Issue Encountering a crash in my Next.js/React/Node application whenever I utilize import Chart from "react-apexcharts" in any file. Upon attempting to access the app, an error message is displayed: Server Error ReferenceError: window is not ...

Passing props to children in the Next JS Layout component is a crucial aspect of

I recently came across a code snippet that effectively resolved my re-rendering issue in Next JS when switching pages. However, I am now faced with the challenge of sending props to the children component. In my layout.js file, I have managed to send props ...