Search code examples
javascripttouchdom-eventstouch-event

Detecting special Javascript touch events


I need Javascripts code for detecting touch events that are not defined for mobile phone browsers.

For example such as dragging finger from left to right or inversed. Is there any idea or trick to do that? I will be very pleased if you DON'T use jQuery, if it's possible.


Solution

  • Using touch-events itself is pretty straightforward. However, recognizing gestures will require custom code.

    Simple example of adding touch events to the window:

    window.addEventListener("touchstart", touchStart, false)
    window.addEventListener("touchmove", touchMove, false)
    window.addEventListener("touchend", touchEnd, false)
    window.addEventListener("touchcancel", touchCancel, false)
    window.addEventListener("touchleave", touchLeave, false)
    
    //  these functions will run when the events are triggered:
    function touchStart(e)
    {
        var x = e.touches[0].pageX
        var y = e.touches[0].pageY
        //  do more stuff...
    }
    function touchEnd(e)
    {
        //  ...
    }
    //  etc. ...
    

    Recognizing a very simple horizontal swipe might like look something like this:

    //  (don't forget the event listeners)
    
    var xStart, yStart
    
    function touchStart(e)
    {
        xStart = e.touches[0].pageX
        yStart = e.touches[0].pageY
    }
    function touchEnd(e)
    {
        var xEnd = e.touches[0].pageX, yEnd = e.touches[0].pageY // store the pageX and pageY in variables for readability
    
        if(Math.abs(yStart - yEnd) < 100) // if there was not a lot of vertical movement
        {
            if(xEnd - xStart > 200) // at least 200 pixels horizontal swipe (to the right)
            {
                swipeLeftToRight() // swipe recognized
            }
            else if(xEnd - xStart < -200) // at least -200 pixels of horizontal swipe (to the left)
            {
                swipeRightToLeft() // swipe recognized
            }
        }
    }
    function swipeLeftToRight()
    {
        alert("You swiped from the left to the right!")
    }
    function swipeRightToLeft()
    {
        alert("You swiped from the right to the left!")
    }
    

    Keep in mind that this very simple example does NOT take into account what the user's finger did in between the starting point and the end point. So in this case the functions would be triggered wether the used drew a straight line across, or drew a half circle for example. Any more complex or more accurate gesture recognitions should keep track of the finger during the whole drag (touchmove).