Unfortunately there is still no eventListener for touch swipes. At least as far as I know.
But I came up with a super simple solution, that works pretty fine for me.
I needed it for a simple sliding gallery, that has buttons for mouse control and also reacts on your arrow keys. But on a phone, I assume you don't want to touch on those tiny buttons, but just swipe the whole thing.
I won't go into details of the slider programming. Let's say you have allready functions for sliding forward and backward through it and your swipe event should just call those.
My solution is super simple (have I already told you that?)
When there is a touch start on the containing element of my sliding gallery, I just lock the "mouse" position. I use pageX as I'm just interested in the relative difference of the mouse position on touch start and touch end, not the position in relation to any of my pages elements.
changedTouches is an array of multiple touches. We just want to track the first finger/touch.
var startXPos = 0;
var startYPos = 0;
function lock(e) {
startXPos = e.changedTouches[0].pageX;
startYPos = e.changedTouches[0].pageY;
}
_container.addEventListener('touchstart', lock, false);
On release, I get the position again, and compare the two values. If the vertical (Y) distance is bigger than the horizontal (X) distance, I assume a scroll attempt, not a side swipe. If the x value is too small I also assume there was no swiping attempt.
function move(e) {
var newXPos = e.changedTouches[0].pageX;
var newYPos = e.changedTouches[0].pageY;
if ((Math.abs(newXPos-startXPos)>Math.abs(newYPos-startYPos)) && (Math.abs(newXPos-startXPos) > 30)) {
if (newXPos - startXPos > 0) {
slideLeftFunction();
} else if (newXPos - startXPos < 0) {
slideRightFunction();
}
}
}
_container.addEventListener('touchend', move, false);
That's it. Nothing more is needed (at least in current browsers).