Joakim Strandell
Joakim Strandell

Reputation: 81

Stop child from triggering parent event in hammer.js

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?

Upvotes: 2

Views: 3593

Answers (2)

Akshay K Nair
Akshay K Nair

Reputation: 1476

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.');
})

Upvotes: 2

Guglie
Guglie

Reputation: 2441

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.

Upvotes: 0

Related Questions