Search code examples
javascriptgoogle-closure-library

Detecting the slide direction with javascript


Looking for a way to use TOUCHEND, TOUCHSTART events to allow the user to scroll through the pages with slide gestures. I don't know how to determine the direction(e.g. get the coordinates of the TOUCHEND and TOUCHSTART points to determine the direction).


Solution

  • Conceptually, you can do this:

    1. Register event handlers for the touchstart and touchend.
    2. On touchstart, you store the x and y coordinates of a particular finger in a persistent variable.
    3. On touchend, you compare the x and y coordinates to the previously saved values.
    4. if Math.abs(deltaX) is more than some min threshold and Math.abs(deltaX) > Math.abs(deltaY), then the gesture is left/right. If xEnd is greater than xBegin, then you're moving left to right, otherwise right to left.
    5. If Math.abs(deltaY) is more than some min threshold and Math.abs(deltaY) > Math.abs(deltaX), then the movement is up/down. If yEnd > yBegin, then it's down, otherwise up.
    6. If neither direction is more than the min threshold, then the gesture wasn't big enough to represent a slide gesture.

    See here on MDN for info about the data for the touch events. MDN is always the first place I look for this kind of stuff.