Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Touches

0.00/5 (No votes)
2 Feb 2013Apache2 min read 7.4K  
Some useful JavaScript code.

I wrote a little web page that “debugs” HTML 5 touch interface (requires touch screen device). Unlike regular mouse clicks, there is no “onTouch” attribute, you have to add and remove listeners via addEventListener() method of a DOM element. The event name is passed as string, which is not very safe, but hey, it’s JavaScript, folks! Nothing is saved there.

Another quirk is that unlike MouseUp notification in various graphic systems, touchend event does not give you coordinates. In some way this makes sense, because the mouse has only one on-screen cursor, and touch interface must support multiple touches. By the time of touchend the number of current touches is zero, which is reflected in the event.

Unfortunately, this means that even if you are only interested in the start and end point of a touch, you still must monitor the touchmove event.

I tested the app on three different phones and here are the results:

Motorola Droid Razr Maxx – can handle virtually any number of touches. The maximum I was able to reach was 12; I am sure the software can handle even more, but we ran out of screen space. Just in case: I ran out of my own fingers at 10 touches and had to use other people’s help to reach 12 :)

IPhone 4S – bails out after 5 touches (go backs to zero if I remember correctly). Not very cool and kinda sloppy, but enough for the vast majority of practical applications.

HTC Droid Incredible – I could not get it to work with more than one touch, because it ignores “user-scalable=no” meta tag. When you touch screen we second finger, the touch event is not passed to the web page, and the page is zoomed instead.

Oh, yeah, and the relevant piece of JavaScript code is below. I did not use jQuery or any similar framework on purpose, to get to the bare bones API.

function reporter(name) {
    return function (e) {
        e.preventDefault();

        var message =
            name + "<br/>" +
            "touches: " + e.touches.length + "<br/>";

        for (var i = 0; i < e.touches.length; ++i) {
            var touch = e.touches[i];
            message += "screenX: " + touch.screenX + "<br/>";
            message += "screenY: " + touch.screenY + "<br/>";
        }

        var info = document.getElementById("info");
        info.innerHTML = message;
    };
}

function report(name) {
    window.addEventListener(name, reporter(name), true);
}

report("touchstart");
report("touchmove");
report("touchend");

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0