Home >Web Front-end >JS Tutorial >How to Temporarily Disable Window Scrolling During jQuery Animations?
When utilizing the scrollTo jQuery plugin, preventing unwanted scrolling during animation is essential for a seamless user experience. While one option is to toggle body overflow, a more refined approach involves disabling the scrollbar while maintaining its visibility.
The scroll event itself cannot be canceled. Instead, consider preventing specific interactions that trigger scrolling, including:
The following JavaScript code achieves this:
// Prevent scroll events function disableScroll() { // Add event listeners for various scroll interactions window.addEventListener('DOMMouseScroll', preventDefault, false); // Older Firefox window.addEventListener('wheel', preventDefault, { passive: false }); // Modern desktop window.addEventListener('touchmove', preventDefault, { passive: false }); // Mobile window.addEventListener('keydown', preventDefaultForScrollKeys, false); // Keyboard } // Re-enable scroll events function enableScroll() { // Remove event listeners for scroll interactions window.removeEventListener('DOMMouseScroll', preventDefault, false); window.removeEventListener('wheel', preventDefault, { passive: false }); window.removeEventListener('touchmove', preventDefault, { passive: false }); window.removeEventListener('keydown', preventDefaultForScrollKeys, false); } // Function to prevent event default action function preventDefault(e) { e.preventDefault(); } // Function to prevent default for specific keyboard scroll keys function preventDefaultForScrollKeys(e) { const scrollKeys = [37, 38, 39, 40]; // Arrow keys if (scrollKeys.includes(e.keyCode)) { e.preventDefault(); } }
To disable scrolling, call disableScroll(); to re-enable it, call enableScroll().
The above is the detailed content of How to Temporarily Disable Window Scrolling During jQuery Animations?. For more information, please follow other related articles on the PHP Chinese website!