Search code examples
javascriptresponsivenav

Prevent scrolling when mobile nav menu is open?


I have a simple nav menu opened from a burger. Whilst this is open how can I prevent all scrolling on the screen? The nav bar is 100vh and I want to prevent scrolling past it whilst it is open?

Js for the nav menu so far (nothing for scrolling)

const navSlide = () => {
    const burger = document.getElementById('burger')
    const nav = document.getElementById('nav')
    const navLinks = document.querySelectorAll('.nav-links li')
    
    burger.addEventListener('click', () => {
        nav.classList.toggle('nav-active')
        navLinks.forEach( (link, index) => {
            if (link.style.animation) {
                link.style.animation = ''
            } else {
                link.style.animation = `navLinkFade 0.7s ease forwards ${index / 7 + 0.4}s`
                }
    })
    burger.classList.toggle('toggle')
  })
}

navSlide()

Solution

  • Add overflow-y: hidden to the body element when the menu is open and remove it when you close the menu.

    When opening:

    document.body.style.overflowY = 'hidden';
    

    When closing:

    document.body.style.overflowY = 'visible';
    

    EDIT:

    You can use the above examples like:

    document.body.style.overflowY = document.body.style.overflowY === 'hidden' ? 'visible' : 'hidden'; // if current styling is *hidden* then change to visible, otherwise change to hidden
    

    As you are toggling the class for the navbar, I think it would be easier for you to toggle a class for the body element too. So you can add following code to your project:

    burger.addEventListener('click', () => {
      document.body.classList.toggle('no-scroll')
      nav.class...
    })
    

    And create a CSS class named no-scroll:

    .no-scroll {
      overflow-y: hidden;
    }