Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save humana-fragilitas/99380b2ba9da8d92ed1c to your computer and use it in GitHub Desktop.
Save humana-fragilitas/99380b2ba9da8d92ed1c to your computer and use it in GitHub Desktop.
Hammer.JS event delegation
/**
* Problem: an Hammer.JS instance listens to the horizontal swipe gestures
* targeted at a top-level html element (e.g.: body) in order to show/hide
* an off-canvas menu; it should be possible to browse a touch-enabled carousel
* placed in the same page (e.g.: RoyalSlider, Owl Carousel or similar) without
* interfering with the above listener.
*
* Solution: enable Hammer.JS custom DOM events and prevent any "swipe" gesture
* from bubbling up to the body element by stopping event propagation via listeners
* attached to each nested touch-enabled element (e.g.: the carousel)
*/
var $body = $('body');
// the Hammer.on() static utility method is a wrapper around addEventListener():
// we are in fact dealing with custom DOM events (http://hammerjs.github.io/api/#utils),
// not to be confused with recognizers events (http://hammerjs.github.io/api/#hammer.recognizer)
Hammer.on($body[0], 'swipe', function(evt){ /* handle the gesture event here; e.g.: show/hide an off-canvas menu */ });
$('.hammerjs-no-swipe').each(function(index, htmlElement){
Hammer.on(htmlElement, 'swipe', function(evt){ evt.stopPropagation(); });
});
$body.hammer({ domEvents: true });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment