Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: detect OS X "natural scroll" settings

I'm facing an issue. For a project I'm doing I'm detecting the scrollwheel position and based on that I'm navigating to the next slide or not. A problem is, however, that some Mac users use "natural scroll" - inverting their scrolling on pages. This means that, for those users, I should use scroll in the other direction as trigger.

My question is; is there a way to detect in what direction the user is used to scroll? My initial idea was to track scrolling and see how scrollTop and scrollwheel relate to each other (i.e., I record mousewheel events and see which direction the page scrolls as a result). That, however, requires the user to scroll before I know what to do. Which doesn't work, as users first need to trigger a slide change.

I'm at a loss. All help is appreciated.

like image 410
Fabdrol Avatar asked Feb 24 '14 10:02

Fabdrol


1 Answers

There's actually an easy answer, as long the Mac users are using Safari--

function myWheelEventHandler(event) {
  var deltaY = -event.wheelDeltaY;
  if (event.webkitDirectionInvertedFromDevice) deltaY = -deltaY;
  // use value for something
}

In this example, the value of deltaY will be positive when the user rolls the mouse wheel away from them (or the trackpad equivalent), and negative otherwise, regardless of the system-wide "natural" scroll setting.

In other words, if the webkitDirectionInvertedFromDevice property is present and has the value true, then you can be sure "natural" scrolling is enabled. It even updates if the setting changes while your script is running. The property is available for wheel events only (not scroll events).

If the property is not present, or is present but has the value "false" (which will always be the case in Chrome, due to a bug), then unfortunately you don't know if the scroll direction is reversed or not.

Your idea of testing to see how the page moves on wheel events may be the most robust solution. You could create an invisible (empty) div in front of your slideshow, set to overflow:scroll, with a taller empty div inside it. The first time you receive a wheel event on this div, you could then work out the scroll direction and trigger the appropriate slide change.

like image 143
bobtato Avatar answered Oct 04 '22 01:10

bobtato