Delegating Hammer.js events with jQuery

will picture will · Apr 17, 2012 · Viewed 7.2k times · Source

I have started using Hammer.js (https://github.com/eightmedia/hammer.js) which is a great little script, but I'm unsure how to delegate the events using jQuery's .on() event handler.

I've set up a little jsfiddle example here: http://jsfiddle.net/will/3dUKu/1/

var i = 0;
// How would I apply hammer to this situation?
$('nav').on('click', 'button', function() {
    $('<button id="' + i + '">Extra button ' + i + ' (' + $(this).attr('id') + ')</button>').appendTo('nav');
    i++;
});

Answer

JoeFlash picture JoeFlash · Jul 21, 2013

Don't know if you ever found an answer to your question. The solution is simple and two part. First, since you are trying to use the calls with jQuery you should use the jQuery plugin version of Hammer. A current version of the jQuery plugin can be found at:

http://eightmedia.github.io/hammer.js/dist/jquery.hammer.min.js

The second part is you need to use Hammer's method with the object selection. You do this by inserting the Hammer call between the selector and the binding. Like so:

jQuery object:

$('nav').on('click', 'button', function(){ 
    /* ... */ 
});

jQuery Hammer object:

$('nav').hammer().on('click', 'button', function(){
    /* ... */
});

That's it...