Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hammer.js breaks vertical scroll when horizontal pan

I'm using Hammer.js to look for horizontal pan gestures, I've devised a simple function to clicks a button when panned left or right. It works okay, except the vertical scroll doesn't do anything on a touch device, or it's really glitchy and weird.

Here's the function:

var panelSliderPan = function() {
    // Pan options
    myOptions = {
        // possible option
    };

    var myElement = document.querySelector('.scroll__inner'),
        mc = new Hammer.Manager(myElement);
    mc.add(new Hammer.Pan(myOptions));

    // Pan control
    var panIt = function(e) {
        // I'm checking the direction here, my common sense says it shouldn't
        // affect the vertical gestures, but it blocks them somehow
        // 2 means it's left pan
        if (e.direction === 2) {
            $('.controls__btn--next').click();
        // 4 == right
        } else if (e.direction === 4) {
            $('.controls__btn--prev').click();
        }
    };

    // Call it
    mc.on("panstart", function(e) {
        panIt(e);
    });
};

I've tried to add a horizontal direction to the recognizer but it didn't really help (not sure if I did it even right):

mc = new Hammer.Manager(myElement, {
    recognizers: [
        [Hammer.Pan,{ direction: Hammer.DIRECTION_HORIZONTAL }],
    ]
});

Thanks!

like image 657
any_h Avatar asked Feb 11 '26 21:02

any_h


2 Answers

Try setting the touch-action property to auto.

mc = new Hammer.Manager(myElement, {
    touchAction: 'auto',
    recognizers: [
        [Hammer.Pan,{ direction: Hammer.DIRECTION_HORIZONTAL }],
    ]
});

From the hammer.js docs:

When you set the touchAction to auto it doesnt prevent any defaults, and Hammer would probably break. You have to call preventDefault manually to fix this. You should only use this if you know what you're doing.

like image 117
patforna Avatar answered Feb 17 '26 12:02

patforna


User patforna is correct. You need to adjust the touch-action property. This will fix scrolling not working when you have hammer bound on a big element in mobile.

You create a Hammer instance like so

var h = new Hammer(options.contentEl, {
    touchAction : 'auto'
});

I was working on a pull to refresh feature, so I need the pan event.

Add the recognizers.

h.get( 'pan' ).set({
    direction   : Hammer.DIRECTION_VERTICAL,
});

h.on('panstart pandown panup panend', eventHandler);

Inside the eventhandler, you'd look at the event that was triggered and manually call on event.preventDefault() when you require it. This is applicable for hammer 2.0.6.

For anyone who's looking the pull to refresh code was taken from - https://github.com/apeatling/web-pull-to-refresh

like image 40
JohnP Avatar answered Feb 17 '26 10:02

JohnP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!