Greg
Greg

Reputation: 10342

Detect desktop Safari's two-fingered swipe

In Safari on OS X, with a magic trackpad or macbook trackpad, swiping right or left with two fingers effects back and forward, respectively. Is there a way to detect this, as distinct from clicking back/forward, or hitting command+arrow etc?

The reason is that the swipe has it's own reveal-style swiping animation, and with custom ajax transitions on a site, it looks really weird when you get one following the other. This happens when browsing code on github, for example.

Update 23/6/16: Github reverted to simply swapping out the page content with no transition, which was a smart move. My current practice is to do the same for back/forward, even if some sort of fancy transition in is use on the site. This prevents clashes between whatever the browser might do and the site transition

Upvotes: 9

Views: 6306

Answers (2)

Brian Tucker
Brian Tucker

Reputation: 310

In a word, no. The swipe is written into the UNIX code behind OS X and into the code of the Safari browser. The browser then recognizes the gesture and interprets it to be the back/forward buttons.

That said, you could probably write some code that would recognize a scrolling on the page of a certain velocity which would then trigger your code, but you'd always be in competition with the pre-coded back/forward button recognition of the browser. To my knowledge, you can't modify the browser from within HTML (or any other language, for that matter).

Upvotes: -2

RaphKomjat
RaphKomjat

Reputation: 186

You can use the mousewheel event to see if an horizontal scroll on the trackpad has been performed before your popstate event:

// boolean that stores if a swipe has been performed.
var bScrolled = false;
// countdown in ms before resetting the boolean.
var iTime = 1000;
var oTimeout;
window.addEventListener('mousewheel', function(e) {
  if (e.wheelDeltaY === 0) {
  // there is an horizontal scroll
    if (!bScrolled) {
    // no need to set bScrolled to true if it has been done within the iTime time. 
      bScrolled = true;
      oTimeout = setTimeout(function(){
        bScrolled = false;
      }, iTime);
    }
  }
});

window.onpopstate = function() {
  // clear the timeout to be sure we keep the correct value for bScrolled
  clearTimeout(oTimeout);
  // check if there has been a swipe prior to the change of history state
  if (bScrolled) {
    // check which browser & OS the user is using, then
    // trigger your awesome custom transition.
  }
}

Upvotes: 9

Related Questions