Home > Web Front-end > JS Tutorial > How to Temporarily Disable Window Scrolling During jQuery Animations?

How to Temporarily Disable Window Scrolling During jQuery Animations?

Barbara Streisand
Release: 2024-12-17 16:55:11
Original
298 people have browsed it

How to Temporarily Disable Window Scrolling During jQuery Animations?

Disabling Window Scrolling Temporarily

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.

Solution: Canceling Scroll Interactions

The scroll event itself cannot be canceled. Instead, consider preventing specific interactions that trigger scrolling, including:

  • Mouse and touch scroll (for mobile devices)
  • Keyboard buttons associated with scrolling (e.g., arrow keys, page up/down, home, end)

Implementation

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();
  }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template