see whatever…

jump to menu

October 3, 2012

Touch handling in Windows 8 JS app

Filed under: CSS,HTML5,Javascript,Win8 — see @ 9:12 pm

Documentation for handling touch in Windows 8 style (Metro ;) apps with Javascript is not really sparse but nevertheless or maybe because of that a total mess. Lots of decriptions of classes (random links…),¬† some blog posts, a few samples which all seem very complicated and a few (better) pointers can even be found at StackOverflow (where else ;) .

Guess as until now I only used wrapper libs like Zepto or a few jQuery plugins for mobile touch handling (mostly iOS) which abstract the hard parts away I expected the code to handle a simple swipe left/right to be simpler.

After playing around a few hours, being lost in the depths of the Microsoft docs I came up with this:

 // define GestureRecognizer
 var recognizer = new Windows.UI.Input.GestureRecognizer();
 recognizer.gestureSettings = Windows.UI.Input.GestureSettings.manipulationTranslateX
 recognizer.addEventListener('manipulationcompleted', function (e) {
   var dx = e.cumulative.translation.x
   // **actually do something, left or right defined by dx > 0 or < 0**
 });

 // actual element which feeds the GestureRecognizer
 var processUp = function (args) {
   try {
     recognizer.processUpEvent(args.currentPoint);
   }
     catch (e) { } // translateYfails ?!
   }
 var swiper = document.querySelector('.swipearea')
 swiper.addEventListener('MSPointerDown', function (args) {
   try {
     recognizer.processDownEvent(args.currentPoint);
   }
     catch (e) { } // translateYfails ?!
   }, false);
 swiper.addEventListener('MSPointerMove', function (args) {
   try {
     recognizer.processMoveEvents(args.intermediatePoints);
   }
     catch (e) { } // translateYfails ?!
   }, false);
 swiper.addEventListener('MSPointerUp', processUp, false);
 swiper.addEventListener('MSPointerCancel', processUp, false);

All in all and in the end almost logical. You preprare a GestureRecognizer and feed it with events from a DOM element. This actually seems capable of doing lots of much more advanced stuff but for a simple swipe left/right gesture seems almost overkill. I wonder if there is something simpler?

In addition I do not understand why the recognizer feeding methods like recognizer.processUpEvent do actually raise an exception if in the above case a up/down swipe is used. One reason is that the element actually has a normal overflow, so the normal scrolling works there. This is the reason the recognizer is set up to only actually handle manipulationTranslateX gestures. But why the additional exceptions?

Anyway, the above seems to work (at least on my desktop and the simulator with both Mouse and BasicTouch mode). Not the simple stuff I have hoped for but maybe I did it all too complicated? Any hints are very much appreciated :)

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress