Multiple Element Swipe Gesture

The swipe gesture

It’s pretty standard to bind swipe events to elements. For the game I’m currently writing, I needed to do something a little different. I wanted to be able to allow the user to swipe across multiple elements and handle this in an elegant and resource efficient way.

The solution

After testing many solutions, here’s what I came up with (and I think it’s the optimum solution). I’m using zeptojs and it’s touch module, although this solution would work with jquery (if you insist), you’d just need to swap out the e.touches with e.originalEvent.touches:

1
2
3
4
5
6
7
var multiSwipe = function (e) {
var touch = e.touches[0],
element = $(document.elementFromPoint(touch.clientX, touch.clientY));
// ...
};
$(".parent").bind("touchmove", multiSwipe);

Essentially, I’m binding the touchmove event to a parent element, then detecting which element is at the current touch point each time the touchmove event is fired. Pretty simple when it’s written for you.

This code is about 10 times smaller than my first attempt and works 10 times faster. document.elementFromPoint is a very effective way to return the topmost element which lies under a given point.

Hammer got it wrong, you can touch this.