Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

HTML, CSS, NextJS – How can I prevent scroll freeze when a page is in desktop mode?

I have a single page application using NextJS.
I use useEffect to hide nav-menu by changing body className as below code:

const [ navbarOpen, setNavbarOpen ] = useState(false);
  const ref = useRef();
  useEffect(() => {
    const handler = (e) => {
      if (
        navbarOpen &&
        ref.current &&
        !ref.current.contains(e.target)
      ) {
        setNavbarOpen(false);
      }
      
    };

    document.body.className = navbarOpen ? '' : 'mobile-nav-active';
    
  }, [navbarOpen]);

and CSS property:

.mobile-nav-active {
  overflow: hidden;
}

In desktop mode, when I click the menu, body className is changed to "mobile-nave-active" then I cannot scroll up or down.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I set the body property only in mobile mode?

Refer to page: https://mairesume.vercel.app

>Solution :

I think the problem is from this line of the code :

 document.body.className = navbarOpen ? '' : 'mobile-nav-active';

it works in desktop and mobile the same but the way that you are treating menu is different in each one,

if you add condition for mobile checking before assigning mobile-nav-active (because you don’t need it to be applied in desktop mode) your problem will be fixed

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
   document.body.className = navbarOpen ? '' : 'mobile-nav-active';
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading