How to stopPropagation() w/ Hammer.js 2.0?

Eric picture Eric · Sep 25, 2014 · Viewed 10.9k times · Source

I have a parent and child div. Panning/dragging on the child should not affect the parent. This is a similar question but was asked a year ago, and I'm using a newer version of Hammer.js w/ the jQuery wrapper.

My assumption was that I'd have to somehow stopPropagation() but I'm not really sure how to use it.

I've mocked up a demo showing my problem on JsFiddle. I've also commented out the couple things I've tried.

$(".outer-box").hammer().bind("panright", function(event){
    // do stuff when panning
    // panning here should move both boxes
});
$(".outer-box").hammer().bind("panend", function(event){
    // do stuff when panning ends
});

$(".inner-box").hammer().bind("panright", function(event){
    // do stuff when panning
    // panning here should only affect the inner box
});
$(".inner-box").hammer().bind("panend", function(event){
    // do stuff when panning ends
});

Any suggestions or tips? Thanks!

Answer

gtzilla picture gtzilla · Aug 23, 2016

In Hammer 2.0.6, as others have answered, you can call event.srcEvent.stopPropagation(). One caveat, you have to set domEvents=true as per the documentation.

Hammer is able to trigger DOM events with the option domEvents: true. This will give your methods like stopPropagation(), so you can use event delegation. Hammer will not unbind the bound events.

Sample Code

var mc = new Hammer.Manager(elem);
mc.options.domEvents=true; // enable dom events
var pinch = new Hammer.Pinch();
mc.add(pinch);
mc.get('pinch').set({ enable: true });
mc.on("pinch",function(e){e.srcEvent.stopPropagation();});

or

var hammertime = new Hammer(elem);
hammertime.domEvents = true;
hammertime.on("panstart", function(e){e.srcEvent.stopPropagation();});

This technique is listed on the tips page of the docs, here http://hammerjs.github.io/tips/