Prevent scrolling when mobile nav menu is open?
Asked Answered
C

1

5

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()
Catch answered 18/2, 2021 at 11:21 Comment(0)
K
7

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;
}
Karaganda answered 18/2, 2021 at 11:28 Comment(3)
thank you, i have tried this and it wont work! Where in the code should I place this? Or create a new listener?Catch
@DanWilstrop You need to insert it into the event listener you already have, but then you would need to check if there is already the class attached to body. Therefore I think it's easier if you use the method I added to the answer attaching a CSS class to body.Karaganda
thanks very much. Got it working, i needed to add position:fixed as well as overflow:y to the class but that works perfectly! Appreciate the helpCatch

© 2022 - 2024 — McMap. All rights reserved.