Search code examples
javascriptmobiletouchhammer.js

hammer js > how to block horizontal panning during page scroll


I've got a page where I put some horizontal slideshows, and have added panning and swipe to them. Sadly, when scrolling on mobile devices, if you scroll above the slideshows, hammer will recognize panning and leave slideshows a little panned... Not so beautiful. I'm thinking about various solutions, but the most obvious maybe would be to stop panning during scroll. Is it possible some way? Here's an extract of my current code (sorry there are methods coming from the parent class..):

if(this.options.touch_enabled){
  this.hm = new Hammer(this.panels_box, {
    recognizers: [
      [Hammer.Swipe,{ direction: Hammer.DIRECTION_HORIZONTAL, threshold: 80 }]
      ,[Hammer.Pan,{ direction: Hammer.DIRECTION_HORIZONTAL, threshold: 80 }, ['swipe']]
    ]
    ,domEvents: false
  });

  this.hm.on('swipeleft', function(e){ if(this.options.next_condition()) this.goto('next', null, true); }.bind(this));
  this.hm.on('swiperight', function(e){ if(this.options.prev_condition()) this.goto('prev', null, true); }.bind(this));
  this.hm.on('panstart', function(e){ this.disable_transition(); }.bind(this));
  this.hm.on('panend', function(e){ this.enable_transition(); }.bind(this));

  this.hm.on('panleft', function(e){
    if(!this.options.loop){ if(this.data_box.getAttribute('data-current') >= this.bounds.end) return; }
    this.panels_strip.style.setProperty('--distance', e.deltaX + 'px');
  }.bind(this));
  this.hm.on('panright', function(e){
    if(!this.options.loop){ if(this.data_box.getAttribute('data-current') <= 0) return; }
    this.panels_strip.style.setProperty('--distance', e.deltaX + 'px');
  }.bind(this));
}// touch

Solution

  • Solution for me was to check deltaY and deltaX, along with event type (since the issue was not found on desktop computers). Here an extract:

    this.hm.on('panleft', function(e){ // ...and same for panright
       if(e.pointerType == 'touch' && (Math.abs(e.deltaY) > Math.abs(e.deltaX))){ return false; }
       // do stuff
    }