Any way to prevent horizontal scrolling triggering swipe back gesture on OS X Lion Safari?

In order to allow an element (e.g. a <div>) to scroll with a trackpad but prevent the browser from going back to the previous page, you need to prevent the browser's default action.

You can do this by listening to the mousewheel event on the element. Using the scroll properties of the element and the deltaX/Y properties on the event, you can prevent and stop the default action when it goes below zero or above the width/height.

You can also use the delta information to manually scroll when you are preventing the whole scroll operation. This allows you to actually get to zero rather than stopping at 10 pixels or something.

// Add the event listener which gets triggered when using the trackpad 
element.addEventListener('mousewheel', function(event) {
  // We don't want to scroll below zero or above the width and height 
  var maxX = this.scrollWidth - this.offsetWidth;
  var maxY = this.scrollHeight - this.offsetHeight;

  // If this event looks like it will scroll beyond the bounds of the element, prevent it and set the scroll to the boundary manually 
  if (this.scrollLeft + event.deltaX < 0 || 
     this.scrollLeft + event.deltaX > maxX || 
     this.scrollTop + event.deltaY < 0 || 
     this.scrollTop + event.deltaY > maxY) {

    event.preventDefault();

    // Manually set the scroll to the boundary
    this.scrollLeft = Math.max(0, Math.min(maxX, this.scrollLeft + event.deltaX));
    this.scrollTop = Math.max(0, Math.min(maxY, this.scrollTop + event.deltaY));
  }
}, false);

This works on Chrome, Safari, and Firefox on Mac. I haven't tested on IE.

This solution will only affect the element in question and will let the rest of the page behave as normal. So you can use your browser as expected and go back a page, but while inside the element you won't accidentally go back when you didn't mean to.


I've been looking for a solution for days. What I have so far is in this plugin:

https://github.com/micho/jQuery.preventMacBackScroll

It disabled scrolling for OSX Chrome (I couldn't find a way to disable it for OSX Safari) when you scroll left and up.

I hope that helps, please contribute to the project with any bugs you find, or if you find a way to disable this annoying behavior for Safari


Yes, in order to disable default behavior (swipe, pinch etc.) all you have to do is to add:

event.preventDefault();

In you case simply register touchMove listener and use preventDefault() there (in function "touchmove").

element.addEventListener("touchmove", touchMove, false);