Home >Web Front-end >JS Tutorial >How to Temporarily Disable Scrolling in JavaScript without Hiding the Scrollbar?

How to Temporarily Disable Scrolling in JavaScript without Hiding the Scrollbar?

Barbara Streisand
Barbara StreisandOriginal
2024-12-21 01:45:10220browse

How to Temporarily Disable Scrolling in JavaScript without Hiding the Scrollbar?

How to Temporarily Disable Scrolling

One way to temporarily disable scrolling while using the scrollTo jQuery plugin is to adjust the CSS of the "body" element. However, this approach can hide the scrollbar, which may not be desirable.

A more effective solution is to prevent specific interaction events from triggering scrolling. These events include:

  • Mouse scroll
  • Touch scroll
  • Buttons associated with scrolling

To implement this solution, you can use the following JavaScript code:

// Disable scrolling
function disableScroll() {
  window.addEventListener('DOMMouseScroll', preventDefault, false); // older FF
  window.addEventListener('wheel', preventDefault, { passive: false }); // modern desktop
  window.addEventListener('touchmove', preventDefault, { passive: false }); // mobile
  window.addEventListener('keydown', preventDefaultForScrollKeys, false);
}

// Enable scrolling
function enableScroll() {
  window.removeEventListener('DOMMouseScroll', preventDefault, false);
  window.removeEventListener('wheel', preventDefault, { passive: false }); 
  window.removeEventListener('touchmove', preventDefault, { passive: false });
  window.removeEventListener('keydown', preventDefaultForScrollKeys, false);
}

This code sets event listeners on the window element to prevent default scrolling actions from being triggered. When you need to disable scrolling, call the disableScroll() function; to re-enable scrolling, call the enableScroll() function.

This approach allows the scrollbar to remain visible but prevents it from being used for scrolling. It also works across a wide range of browsers.

The above is the detailed content of How to Temporarily Disable Scrolling in JavaScript without Hiding the Scrollbar?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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