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
Release: 2024-12-21 01:45:10
Original
219 people have browsed it

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

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!

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