Prevent page navigation on horizontal scroll

6.3k views Asked by At

I am using a mac trackpad.How to prevent the page going back and next to visited pages on horizontal scroll ?.

I tried to prevent the wheel events but it doesn't works most of the time.

container.addEventListener('wheel', function(ev) {
    ev.preventDefault();
    ev.stopPropagation();
    return false;
}, {passive: false, capture: true});

even I tried blocking with mousewheel event which also leads to page navigation.

2

There are 2 answers

10
Maciej Kwas On

It has nothing to do with a webpage nor its events; this is specific system behavior and I don't think it can be blocked from javascript level.

If you want to disable it - go to: Apple Logo > Preferences > Trackpad > More gestures and uncheck Swipe between pages

// EDIT

Ok, I googled a bit and it seems I was wrong- there is a solution to that and basically is pretty simple:

document.body.addEventListener('mousewheel', function(e) {
  e.stopPropagation();
  var max = this.scrollWidth - this.offsetWidth; // this might change if you have dynamic content, perhaps some mutation observer will be useful here

  if (this.scrollLeft + e.deltaX < 0 || this.scrollLeft + e.deltaX > max) {
    e.preventDefault();
    this.scrollLeft = Math.max(0, Math.min(max, this.scrollLeft + e.deltaX));
  }
}, false);

Just tested this on OSX Chrome 67

2
Charles Holbrow On

As of 2022 this can be managed in all browsers with the overscroll-behaviour CSS property: https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior

For example:

body {
  overscroll-behavior-x: contain;
}

Or, you could apply it just on a single element that has overflow scroll, allowing swipe navigation in the rest of the page, just blocking it in the portion they would be scrolling:

.someScrollingComponent {
  overflow: scroll;
  overscroll-behavior: contain;
}

The MDN docs describe property contain:

Default scroll overflow behavior (e.g., "bounce" effects) is observed inside the element where this value is set. However, no scroll chaining occurs on neighboring scrolling areas; the underlying elements will not scroll. The contain value disables native browser navigation, including the vertical pull-to-refresh gesture and horizontal swipe navigation.

(Emphasis added)