Why is binding hammer.js to document body not working? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Why is binding hammer.js to document body not working? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I want to use hammer.js to capture mobile touch inputs. As some elements (e.g., some ‘li’) are dynamically generated, I want to bind the hammer object to document itself, and use a selector to capture the events.

var hammer=Hammer(document.body);
hammer.on("release",'.touchzone',function(ev){
  alert(ev.gesture);
});

The code above doesn’t work – there is no alert and the function is not entered. However, I directly attached the hammer object to the element div.touchzone could work.

var hammer=Hammer($('.touchzone')[0]);
hammer.on("release", function(ev){alert(ev.gesture);});

I use jQuery 1.11.0, and the v1.0.9 hammer.min.js (with size of ~13kb).

What could be the possible reason?

Answer

It’s probably because $('.touchzone')[0] return a native DOM object, not a jQuery object.

To apply jQuery along with Hammer, you can make use of jQuery Hammer plugin.

Include it after jQuery, then you can do:

$(document.body).hammer().on('release', '.touchzone', function(ev){
    alert(ev.gesture);
});
We are here to answer your question about Why is binding hammer.js to document body not working? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji