Prevent user scrolling when full-screen menu is activated

Currently, I am developing a full-screen menu for a website and facing an issue with disabling the user's ability to scroll when the menu is open. Despite searching online, I have not found a suitable solution. It would be greatly appreciated if someone could provide assistance as I am unsure how to prevent scrolling in the body element when the menu is active, particularly since my JavaScript knowledge is limited.

Below is the code snippet I am currently working on:

<body id="body">
    <div class="navbar">
        <div class="navbar-wrapper">
            <div class="logo">
                <img src="images/Gautama_Buddha_pic.png">
            </div>
            <nav id="menu">
                <ul>
                    <li><a href="">ARTIST</a></li>         
                    <li><a href="">EXHIBITIONS</a></li>         
                    <li><a href="">EVENTS</a></li>         
                    <li><a href="">VISIT US</a></li>         
                </ul>
                <p class="lite-text">MENU</p>
                <img src="images/close-line.png" class="close-icon" onclick="closemenu()">
            </nav>
            <img src="images/hamburger-menu.png" class="menu-icon" onclick="openmenu()">
        </div>
    </div> 

    <section class="one">
        <h2>Hello World</h2>
    </section>
    <section class="two"></section>
    <section class="three"></section>
    <section class="four"></section>
    <section class="five"></section>
    
<script>
    var menu = document.getElementById("menu");

    function closemenu(){

        menu.style.top = "-100vh";
    }

    function openmenu(){

        menu.style.top = "0";
    }
</script>

</body>

Here's the accompanying CSS:

        *{
    padding: 0;
    margin: 0;
    font-family: sans-serif;
    user-select: none;
}

.container{
    height: 100vh;
    width: 100%;
    background-color: white;
    position: relative;
}

.navbar{
    width: 100%;
    position: fixed;
}

.navbar-wrapper{
    width: 90%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: auto;
}

.logo img{
    width: 50px;
    cursor: pointer;
    margin: 35px 0;
}
...
... (CSS continuation) 
...
    .no-scroll {
    overflow:hidden;
}

Your help is highly valued! Thank you!

Answer №1

To enable scrolling when the menu is opened, I utilized the following code:

document.querySelector('body').classList.add('no-scroll')
. This code removes the ability to scroll when the menu is closed:
document.querySelector('body').classList.remove('no-scroll')
.

        *{
    padding: 0;
    margin: 0;
    font-family: sans-serif;
    user-select: none;
}

.container{
    height: 100vh;
    width: 100%;
    background-color: white;
    position: relative;
}

.navbar{
    width: 100%;
    position: fixed;
}

.navbar-wrapper{
    width: 90%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: auto;
}

.logo img{
    width: 50px;
    cursor: pointer;
    margin: 35px 0;
}

nav ul li{
    list-style: none;
    margin: 35px 0;
}

nav ul li a{
    text-decoration: none;
    font-size: 40px;
    color: white;
    padding: 10px;
    letter-spacing: 5px;
    position: relative;
}

nav ul li a::after{
    content: '';
    height: 3px;
    width: 0%;
    background: #dfa24e;
    position: absolute;
    bottom: 0;
    left: 0;
    transition: width 0.5s;
}

nav ul li a:hover::after{
    width: 100%;
}

nav{
    position: absolute;
    width: 100%;
    height: 100vh;
    background-color: grey;
    z-index: 2;
    top: -100vh;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    transition: 1s;
    overflow: hidden;
}

.lite-text{
    color: transparent;
    font-size: 200px;
    letter-spacing: 100px;
    opacity: 0.1;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    font-weight: 800;
    z-index: -1;
    -webkit-text-stroke: 5px #000;
}

.close-icon{
    width: 25px;
    position: absolute;
    right: 80px;
    top: 50px;
    cursor: pointer;
}

.menu-icon{
    width: 30px;
    cursor: pointer;
}

section{
    height: 100vh;
    width: 100%;
}

.one{
    background-color: tomato;
}
.two{
    background-color: thistle;
}
.three{
    background-color: blue;
}
.four{
    background-color: blueviolet;
}
.five{
    background-color: wheat;
}

    .no-scroll {
    overflow:hidden;
}
<body id="body">
    <div class="navbar">
        <div class="navbar-wrapper">
            <div class="logo">
                <img src="images/Gautama_Buddha_pic.png">
            </div>
            <nav id="menu">
                <ul>
                    <li><a href="">ARTIST</a></li>         
                    <li><a href="">EXHIBITIONS</a></li>         
                    <li><a href="">EVENTS</a></li>         
                    <li><a href="">VISIT US</a></li>         
                </ul>
                <p class="lite-text">MENU</p>
                <img src="images/close-line.png" class="close-icon" onclick="closemenu()">
            </nav>
            <img src="images/hamburger-menu.png" class="menu-icon" onclick="openmenu()">
        </div>
    </div> 

    <section class="one">
        <h2>Hello World</h2>
    </section>
    <section class="two"></section>
    <section class="three"></section>
    <section class="four"></section>
    <section class="five"></section>
    
<script>
    var menu = document.getElementById("menu");

    function closemenu(){
                 
        document.querySelector('body').classList.remove('no-scroll')
        menu.style.top = "-100vh";
    }

    function openmenu(){
        document.querySelector('body').classList.add('no-scroll')
        menu.style.top = "0";
    }
</script>

</body>

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

Exploring the Power of Map with Angular 6 HttpClient

My goal is to enhance my learning by fetching data from a mock JSON API and adding "hey" to all titles before returning an Observable. Currently, I am able to display the data without any issues if I don't use the Map operator. However, when I do use ...

What is the best way to create a backup copy of my project using git?

To ensure the safety of my project, I took the necessary steps to back it up. First, I initialized a repository using git init Following that, I committed all files by executing git add . git commit -am "first commit" Now, the next step involves pushin ...

"Occasionally, the PHP function for randomly selecting an image may result in

My function is supposed to open a specific directory, create an array of the image files within that directory, and then select a random image from the array to display on a webpage. However, there are instances where it fails to retrieve the image name. ...

Verifying the presence of an image via its URL may not be functional across all browsers

Hey folks, I'm working on a project that involves displaying an image along with other fields in a loop where the image source changes with each iteration. I also need to check if the image exists and set a default source if it doesn't. The code ...

Issue 404: Trouble sending form data from React to Express

I'm facing an issue when trying to send form data from a React frontend to my Node.js/Express backend. The problem seems to be related to a 404 error. I've included only the relevant code snippets below for reference. Function for submitting the ...

What is the best way to pass values between JSP Expression Language and Javascript?

I have a request object with the following content: List<Integer> list What is the best way to loop through this list using JavaScript? I am interested in obtaining the values of each element within the list. Note that these list values are not cu ...

Retrieve data from cookies that have been stored by the node server on the front end

I am currently utilizing the Node package 'cookie' to establish cookies from the backend as shown below: res.setHeader('Set-Cookie', cookie.serialize('token', token, { maxAge: 60 * 60 * 24 * 7 // 1 week ...

Prevent automatic merging of JSON data with identical IDs

My AJAX call to a PHP select request is as follows: $.ajax({ type: "POST", url: "/renforts/_getIntervenantManager", data: { IDMission : IDMission, IDManager : IDManager }, dataType : 'json' ...

Attempting to optimize a webpage design for compatibility with Google's mobile-friendly testing tool

After much searching on the forum, this is my first post, so I kindly ask for patience! I am dealing with a 20-year-old website that urgently needs to be optimized for mobile devices. With almost 2200 pages, manual editing is out of the question, so I nee ...

What's the best way to ensure consistent spacing between a label and input field, regardless of the length of the text?

Imagine a scenario where there are 10 input fields, each preceded by a span tag on the left side indicating what should be entered. While working on this setup, I encountered an issue - how can I create a consistent space between the span tag and the input ...

Is there a more effective way to structure my code than using multiple "IF/ELSE" statements?

Here is the current code snippet that I have: (category=="Ljud & Bild") ? byId("nav_sub_ljud_bild").style.display='block' : byId("nav_sub_ljud_bild").style.display='none'; (category=="Datorer") ? byId("nav_sub_datorer").style.disp ...

The complexity surrounding various versions of jQuery, the .noConflict method, and the jQuery migrate feature

I was tasked with making a large-scale website responsive, and decided to utilize Bootstrap as the framework. However, I encountered issues due to the jQuery version (v1.8.2) being used. In my development environment, I resolved this by including the follo ...

Customize arrow direction in AntDVue ant-collapse using simple CSS styling

Is there a way to customize the arrow directions in ant-collapse vue? I recently faced an issue where I couldn't change the arrow directions without using !important (which I try to avoid). Fortunately, we found a workaround for this problem at my wo ...

Tips for aligning pagination in the MUI v5 table component and creating a fixed column

I am currently experimenting with MUI table components and have created an example below with pagination. const MuiTable = () => { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const [data, setData] ...

What is the reason behind Angular's continued use of JSON for encoding requests? (specifically in $http and $httpParamSerializerJ

Is there a way to set Angular to automatically send requests as x-www-form-urlencoded instead of JSON by default? Angular version 1.4.5 I've tried the following code snippet but it doesn't seem to work: angular.module('APP').config( ...

Typescript Angular2 filtering tutorial

In Angular 2 using TypeScript, the goal is to search for matching values from an array within an object array. The intention is to filter out any objects where the 'extraService' property contains any of the values from the 'array_values&apo ...

Display a limited number of characters along with a button on the blog tag pages. Clicking on the button will reveal the complete text description

Hey, I am looking to replicate the way WooCommerce tags descriptions are displayed on my WordPress blog. I want it to show only a certain number of characters with a "show all" link, similar to how it appears on this site: I have found some code that work ...

Troubleshooting: Issues with VueJS Class Binding Functionality

In my form, I have an input field that is validated to check if it is empty or not. If the input field is empty, a red border is applied using class binding. However, when the user focuses on the input field after receiving the error, the error message sh ...

Tips for preserving a circular element shape while accommodating dynamic content

I'm attempting to generate a circular shape using the ::after pseudo element, which adjusts its size automatically based on the content inside. .container { display: flex; flex-direction: row; } #dividerHost2 #left { flex: 1 1 auto; ...

"Merging the vibrancy of RGB with the subtlety of

Currently exploring methods to blend an RGB color with a grayscale one. This is for a gradient generator that leverages preset colors and a template (predefined style properties for various vendors) in order to craft a CSS3 gradient. I am certain there is ...