How to handle touch and swipe events on iphone ipad and android

Most of the gadgets we use today are touch screen devices. Its obvious that at some point web developers would need to handle touch events on web pages.

Handling touch is simple. Each type of device expose certain touch event that we have to listen in our script.

Following is the list of those events:

  • touchstart

    Event fires when user touches the screen.

  • touchmove

    Event fires when user moves finger/s on the screen

  • touchend

    Event fires when user removes finger/s from screen

  • touchcancel

    Event fires when user touch anywhere outside client area like on address bar, bookmark icon or start button in ipad.

SWIPE AREA

HTML & Script
<p class="well well-large" id="result" style="width: 100%; height: 300px;">
</p>
<script type="text/javascript">
    var touchStart = function (event) {
        if (event.targetTouches.length > 1) { return; }

        document.getElementById("result").innerHTML = "TouchStart";
    };

    var touchMove = function (event) {

        if (event.targetTouches.length > 1) { return; }
        det = {
            client: { x: event.targetTouches[0].clientX, y: event.targetTouches[0].clientY },
            page: { x: event.targetTouches[0].pageX, y: event.targetTouches[0].pageY },
            screen: { x: event.targetTouches[0].screenX, y: event.targetTouches[0].screenX }
        };

        document.getElementById("result").innerHTML = "TouchMove ( x : " + event.targetTouches[0].pageX + ", y : " + event.targetTouches[0].pageY + ")";
        event.preventDefault();
    };

    var touchEnd = function (event) { document.getElementById("result").innerHTML = "TouchEnd"; };
    var touchCancel = function (event) { document.getElementById("result").innerHTML = "TouchCancel"; };

    document.getElementById("result").addEventListener("touchstart",
        touchStart, false);
    document.getElementById("result").addEventListener("touchmove",
        touchMove, false);
    document.getElementById("result").addEventListener("touchend",
        touchEnd, false);
    document.getElementById("result").addEventListener("touchcancel",
        touchCancel, false);
</script>

if (event.targetTouches.length > 1) { return; } is used in touch start and move function to check if only one finger is touching the surface.

Swipe event needs to programmed. If you want swipe action code please check swipe plugin that I have developed, it will give you the ability to add touch based swipe and mouse based swipe capability to any element.

If you have any queries regarding the topic please feel free to comment in the box below. I'd be happy to help.

Subscribe for our monthly newsletter for updated articles and useful code scripts.

Share It

comments powered by Disqus
Chat With Us Close
Leave Message