Different methods to disable scrolling when the mobile menu pops up

I have implemented a mobile menu option that appears when you click on the triple line logo, but unfortunately, users can still scroll while the menu is open. I've tried using position:fixed; but haven't been successful in preventing scrolling behavior. Please let me know if you have any suggestions on how to fix this issue or if there is an alternative approach. Thank you

function openNav() {
    document.getElementById("myNav").style.width = "100%";
  }
  
  function closeNav() {
    document.getElementById("myNav").style.width = "0%";
  }
  #md1{
    width:100%;
    height:63px;
    background-color: rgb(84, 104, 217);
    top:0;
    position:absolute;
  }
  body {
    font-family: 'Lato', sans-serif;
  }
  .bars{
  color:white;
  }
  .overlay {
    height: 100%;
    position: fixed; /*Changed 'fixed' for correct syntax */
    width: 0;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: rgb(84, 104, 217);
    overflow-x: hidden;
    transition: 0.5s;
  }
  .fixedPosition
  {
     position: fixed;
  }
  .overlay-content {
    position: relative;
    top: 25%;
    width: 100%;
    text-align: center;
    margin-top: 30px;
    color:white;
  }
  .overlay a {
    padding: 8px;
    text-decoration: none;
    font-size: 36px;
    color: white;
    display: block;
    transition: 0.3s;
  }
  
  .overlay .closebtn {
    position: absolute;
    top: 20px;
    right: 45px;
    font-size: 60px;
  }
  
  @media screen and (max-height: 450px) {
    .overlay a {font-size: 20px}
    .overlay .closebtn {
    font-size: 40px;
    top: 15px;
    right: 35px;
    }
  }
.footer {
  position: relative;
  background-color: rgb(84, 104, 217);
  height: 80px;
  top: 546px;
  color: white;
  overflow: hidden;
}

.footwords {
  padding-top: 32px;
  font-family: 'playfair_displayregular';
  position: relative;
  left: 6%;
}
  .dtp {
  display:none;
  }
  .leftimage {
    position: absolute;
    object-fit: cover;
    width: 95%;
    height: 365px;
    top: 67px;
    float:left;
    left:2.5%;
  }
}
<!DOCTYPE html>
<html lang="en">
  <link rel="stylesheet" type="text/css"  href="CSS/styleindex.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <script src='Javascript/index.js'></script>
  <!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-168595753-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-168595753-1');
</script>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>
    Rom Fradkin
  </title>
  <link rel="shortcut icon" type='image/png' href="Images/favicon.png">
</head>

<body>
  <header class="topnav" id="topnav">
    <div class='dtp'>
    <a class="active-menu" href="index.html">Home</a>
    <a class="link" href="Pages/academics.html">Academics</a>
    <a class="link" href="Pages/projects.html">Projects</a>
    <a class="link" href="Pages/communityservice.html">Community Service</a>
  </div>
    <div id='md1'>
      <div class='md'>
        <div id="myNav" class="overlay">
          <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
          <div class="overlay-content">
            <a href="index.html">Home</a>
            <a href="#">Services</a>
            <a href="#">Clients</a>
            <a href="#">Contact</a>
          </div>
        </div>
        
        <span class='bars' style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; </span>
        
    </div>
    </div>
  </div>
  </header>
  <div class='section1'>
    <img class= 'leftimage' src="Images/frontback.jpg" alt="Missing File">
    <div class='HelloIm'>Hello, I'm</div>>
    <div class='romf'>Rin.</div>>
  </div>
  <div class='bio'>
      <img class = 'rndface' src="Images/rndface.png" alt="Missing File">
      <h1 class='topname'>
        Rkin
      </h1>
      <p class='school'>
        Nechool
      </p>
      <p class='interests'>
        Encience
      </p>
      <p class='location'>
        Chicnois
      </p>
      <p class='mail'>
        fril.com
      </p>
      <p class='num'>
        (8
      </p>
      <p>
        <a target="_blank" rel="noopener noreferrer" href="https://www.instagkin/" class="fa fa-instagram"></a>
        <a target="_blank" rel="noopener noreferrer" href="https://www.linkedin.com/inin-a3a9541a5/" class="fa fa-linkedin"></a>
        <a target="_blank" rel="noopener noreferrer" href="https://github.in" class="fa fa-github"></a>
      </p>
      <p>
    </div>
  
  </body>
</html>

Answer №1

One easy way to prevent a page from scrolling when the navigation is open is by changing the overflow style of the body tag to hidden. Then, when the navigation is closed, you can set it back to auto to allow scrolling again.

function openNav() {
  document.getElementById("myNav").style.width = "100%";
  document.getElementsByTagName("body")[0].style.overflow = "hidden"; // include this
}

function closeNav() {
  document.getElementById("myNav").style.width = "0%";
  document.getElementsByTagName("body")[0].style.overflow = "auto"; // include this
}

You can see an example here.

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

The iFrame is set to a standard width of 300 pixels, with no specific styling to dictate the size

My current challenge involves utilizing the iframe-resizer package to adjust the size of an iframe dynamically based on its content. However, even before attempting any dynamic resizing, I encounter a fundamental issue with the basic iframe: it stubbornly ...

Unable to pass on error from Express server to React client app

Background Overview In my project, I've implemented a React component named 'Register.jsx' where users can input their desired username and password. Upon clicking the submit button, this information is transmitted to an Express backend whi ...

Converting HTML and CSS to PDF in Java using iText

I've been working on converting HTML to PDF. Initially, I transformed my HTML code into XHTML using the resources provided in this link: After successfully displaying the generated XHTML code in a browser by creating an HTML file for testing purposes ...

removing duplicate items from an array in Vue.js

I created a Pokemon App where users can add Pokemon to their 'pokedex'. The app takes a pokemon object from this.$store.state.pokemon and adds it to this.$store.state.pokedex. However, users can add the same pokemon multiple times to the pokedex, ...

Differences in rendering of HTML select element between Chrome on macOS and Chrome on Windows

During testing of a section of the app at my workplace, it was discovered that dropdowns and select elements in a specific UI scenario appeared differently on Chrome for Windows and Ubuntu compared to Chrome for macOS. I attempted to analyze the elements ...

"Techniques for incorporating a screen in Angular application (Switching between Edit and View modes) upon user interaction

We are currently working on a screen that requires the following development: This screen will have the following features: When clicking on a button, the fields should become editable. In the image provided, there is some repeated data, but in our case, ...

Tips for setting variable values in Angular 7

I'm encountering an issue with assigning values to variables in my code. Can anyone provide assistance in finding a solution? Here is the snippet of my code: app.component.ts: public power:any; public ice:any; public cake:any; changeValue(prop, ...

HTML border width is set to 100%, but there seems to be an issue with the responsive menu border and icon display

One issue I'm encountering with my website involves the border at the bottom of my navigation bar. Despite trying to adjust the box-sizing property to border-box, I still can't get it to display correctly. My goal is to have the border span 100% ...

Having trouble displaying specific images on React Native, how can I resolve this issue?

I am currently developing a weather application that retrieves weather information and displays it using ForecastItem components. However, I have noticed that some of the components do not display the weather image randomly. On the Home screen, I use the ...

The functionality of the "#Next" and "#Prev" features in the Tiny carousel are currently not functioning properly within the MVC project

Looking to implement a simple content carousel using jQuery 2.1.3 in my project. Previously used a non-responsive jQuery content carousel and switched to find a responsive option:Tiny Carousel Added Tiny Carousel's .js and .css files to Bundles.confi ...

Maintain selected values in a dropdown list that is generated dynamically

I am currently revamping an outdated webpage that pulls data from a database. My main objective is to implement the functionality to let users narrow down their search by selecting certain values. To achieve this, I have developed a dynamic dropdown list ...

The mobile website layout appears immaculate on the emulator, but it doesn't translate well on real mobile devices

Recently, I delved into the world of html/css/javascript and decided to create a website as a way to practice my skills. However, I have come to realize that many of the methods I used are not considered best practices. I am committed to improving and will ...

Using an if-else statement within a Vue event listener

Can this task be achieved using Vue: <button @click="(true) ? funcA : FuncB"> Click </button> In this scenario, the event is a click, however it could also involve keypress, keydown, input or any other events documented in vuejs. If ...

Repetitive bouncing in a trampoline leads to the error message "Call stack has reached maximum size"

I have been delving into the world of blockchain and experimenting with a simple implementation of "proof of work". Proof of work: export function mineBlock(difficulty: number, block) { const prefix = Array(difficulty + 1).join("0"); function mine(b ...

Navigate through the Jquery slider by continuously scrolling to the right or simply clicking

Is there a way to prevent my slider from continuously scrolling? I think it has something to do with the offset parameter but I'm having trouble figuring it out. Any assistance would be greatly appreciated. var $container = $(container); var resizeF ...

Obtaining the Immediate ID of a Widget using JQuery

I currently have the following setup: <div id="dualList"></div> I created a plugin but stripped it down for testing purposes. I am encountering difficulties with the plugin not displaying the ID of the div. <script> (function($) { ...

Is it possible to set up a PHP variable within a JavaScript function?

In the code snippet above, we have a JavaScript function that is used for validation. I am looking to set a PHP variable within the else statement. function validate() { if(document.loginForm.vuser_login.value==""){ alert("Login Name name ca ...

Potential memory leak detected in EventEmitter by Discord.js

One night while my bot was running on auto-pilot as I drifted off to sleep, a warning popped up out of the blue: MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 guildMembersChunk listeners added to [Client]. Use emitter.setMaxLi ...

Cypress 7: Dealing with the onRequest Problem in the cy.intercept Function

We encountered a situation where we needed to assert that a spinner was displayed during a request using the following code: The code functioned properly in Cypress 6.4.0 cy.intercept({ url: '*', onRequest: () => { cy.get('[data- ...

Preventing context menu from appearing on a right click by implementing a trigger to re-enable it

I am looking to implement a functionality on my website that disables the right click menu. Currently, I have achieved this through the following code: document.addEventListener("contextmenu", function(e){e.preventDefault(); }, false); Now, I am wonderin ...