iPad acceleration with Javascript

It’s well known that Apple supports HTML5 from the very beginning, that comes with a lot of advantages for Javascript developers. One of them is knowing the exact position of the iPad using a couple of events.

First of all I have to say I’ve only tested this with an Ipad 2 with iOS 5, but it should work too with the new iPad (a.k.a. iPad 3).

In order to know what’s the position of an iPad we can use the Device Motion Event, specified by the W3C here. For my purpose I only use 3 variables:

window.addEventListener('devicemotion', function (e) {
  x = e.accelerationIncludingGravity.x;
  y = e.accelerationIncludingGravity.y;
  z = e.accelerationIncludingGravity.z;
}, false);

Once we have these variables it’s all about testing and playing with ranges of values. What I did was creating some messages after I detect a certain position, for instance, when the iPad is in landscape or portrait position using a function executed every 10ms.

mainLoop = setInterval("moveMe()", 10);

function moveMe() {
  // here you check what's the value of a, y, and z
  // and it's checked every 10 ms

I know, it would be great to have a little plugin to detect the different positions and trigger events accordingly, but I don’t own an iPad yet so I can only test with borrowed iPads :(