Greg Greg - 1 year ago 114
Javascript Question

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

Answer Source

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
  // 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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download