Detecting a swipe (left, right, top or down) using touch

Swiping in touch is the act of quickly moving your finger
across the touch surface in a certain direction. There is currently no "onswipe" event
in JavaScript, which means it's up to us to implement one using the
available touch events, plus define just when a swipe is a, well, "swipe".

Lets first define when a movement across the touch surface
should be considered a swipe. There are two variables at play here- the
distance traveled by the user's finger on the x or y-axis from touchstart to
touchend, and, the time it took. Based on these two factors, we can decide
whether that action qualifies as a swipe and in what direction.

With that said, lets put ideas into action and see how to
go about detecting a swipe right (from left to right). Once we can do that,
detecting swipe in the other 3 directions is pretty much identical. For this exercise we'll stipulate that a right swipe has
occurred when the user has moved his finger across the touch surface a
minimum of 150px horizontally in 200 ms or less from left to right.
Furthermore, there should be no more than 100px traveled vertically, to
avoid "false positives" whereby the user swipes diagonally across, which we
don't want to qualify as a swipe right.

Inside touchend, we check that the dist traveled from
touchstart to touchend is a positive number above the specified threshold
value (ie: 150), since in a right swipe, that dist should always be positive
based on the equation used (versus negative for a left swipe). At the same
time, we make sure any vertical lateral movement traveled is less than 100px
to weed out diagonal swipes. Since the vertical movement can occur either above
the starting touch point or below, we use Math.abs() when getting the
absolute vertical dist traveled so both scenarios are covered when comparing it to our
vertical threshold value of 100.

A generic swipe detecting function

Now that we
got right swipe down, lets create a more generic function that detects
swiping in either of the 4 directions (left, right, up, or down):

swipedetect() accepts two parameters, the element to bind
the touch events to, plus a function to execute when a swipe has occurred.
The function parameter "swipedir" tells you the type of swipe that was just
made with five possible values: "none", "left", "right", "top", or "down".

The below uses the swipedetect() function to show a "left", "right", "top", or "down"
background image (overlaid on top of a default background image) depending
on the swipe that has just occurred:

We bind swipedetect() to "#touchsurface2",
and whenever a valid swipe has occurred inside it, we change the "#inner"
DIV's background image accordingly to reflect the type of swipe that has
just occurred.