gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
JAVASCRIPT. give me the most modern solution to toggle lock and unlock scroll for body.…
- User
JAVASCRIPT. give me the most modern solution to toggle lock and unlock scroll for body. I need two functions, one function to lock and one to unlock.No additional css just javascript solutin. And the most modern without any bugs
- Assistant
Certainly! Below are two modern JavaScript functions to lock and unlock the scroll for the
body. These solutions use ES6 syntax and make use of modern JavaScript features:// Function to lock the scroll const lockScroll = () => { document.body.style.overflow = 'hidden'; document.body.style.height = '100%'; const scrollBarWidth = window.innerWidth - document.documentElement.clientWidth; document.body.style.paddingRight = `${scrollBarWidth}px`; }; // Function to unlock the scroll const unlockScroll = () => { document.body.style.overflow = ''; document.body.style.height = ''; document.body.style.paddingRight = ''; }; // Usage Example: // lockScroll(); // To lock the scroll // unlockScroll(); // To unlock the scroll