Search code examples
javascriptswipegesturehammer.jsevent-propagation

How to stop Hammer.js from not propagating swipe events?


I have a working markup and script to track horizontal swipes on a container using Hammer.js:

const container = document.getElementsByClassName('swiper')[0];

const manager = new Hammer.Manager(container);
const swipe = new Hammer.Swipe();

manager.add(swipe);

manager.on('swipe', event => {
    if (event.offsetDirection === 4) {
        container.style.background = 'red';
    }

    if (event.offsetDirection === 2) {
        container.style.background = 'blue';
    }
});
.swiper {
    height: 100vh;
    background: grey;
}
<script src="https://hammerjs.github.io/dist/hammer.min.js"></script>
<h1>Some content</h1>

<div class="swiper"></div>

<h1>More content</h1>

Fiddle

https://jsfiddle.net/vzg7fy9q/1/


This works fine and I'm already triggering a slider with that.

However, the problem is, that all swipe-events seem to be prevented. The user can't scroll up or down anymore on a mobile device. I've tested this on an iPhone with iOS 11.


Is there a way to tell Hammer.js to propagate these events instead of consuming them?


Solution

  • I've fixed it by explicitly setting the directions that should be tracked using DIRECTION_HORIZONTAL. I also removed the Hammer.Manager:

    const hammer = new Hammer(container, {});
    
    hammer.get('swipe').set({ direction: Hammer.DIRECTION_HORIZONTAL });
    hammer.on('swipe', event => {
        if (event.offsetDirection === 4) {
            container.style.background = 'red';
        }
    
        if (event.offsetDirection === 2) {
            container.style.background = 'blue';
        }
    });