2

When binding an hammer event to a element, the event is also triggered by it's child element. Using stopPropagation to keep the event from bubbling up doesn't seem to work.

HTML:

<div id="parent">
    <div id="child"></div>
</div>

JS:

var hammertime = new Hammer(document.getElementById('parent'));

hammertime.on('tap', function(e) {
    e.srcEvent.stopPropagation();
    alert('Clicked on ' + e.target.id);
});

See JSFiddle for example: http://jsfiddle.net/qqvyqzgh/3/

What am I missing here?

2 Answers 2

2

Adding to @Guglie's answer, For a more general case, add a class to all elements in children you want to disable the hammer event:

<div>
  Drag me
  <input class='disableHammer' type="range" placeholder="Don't drag me"></input>
</div>

and;

hammertime.on('pan', function(e) {
  if(e.target.classList.contains("disableHammer")) alert('Stop dragging him.');
})
0

You can check if the target of the event is the parent element.

var element = document.getElementById('parent');
var hammertime = new Hammer(element);

hammertime.on('tap', function (e) {
    if(e.target === element) {
        alert('Clicked on ' + e.target.id);
    }
});

Here's your updated fiddle.

2
  • Hi @guglie your answers helped me to get in the right direction. However I have a parent container with lots of child elements. And one of the child element has different event. How would you manage if you have different target value? Thanks Commented Oct 17, 2018 at 23:40
  • Hi @Mesmerize86, if the child which needs to react to tap is only one probably you can just put simply another clause } else if (e.target === child_element) { /*do stuff for child*/ }
    – Guglie
    Commented Oct 19, 2018 at 10:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.