Javascript Accelerometer Demo and Source

IOS 4.2 (with new Safari Mobile) has the possibility to read sensor data like accelerometer and gyroscope directly from Javascript.

New Javascript objects and event handler

From javascript point of view, we have:

  • new handler window.ondevicemotion
  • new event object:
    • event.accelerationGravity, with x, y, z attributes
    • event.accelerationIncludingGravity, with x, y, z attributes
    • event.rotationRate, with alpha, beta, gamma attributes

Code Snip

window.ondevicemotion = function(event) {
	var accelerationX = event.accelerationIncludingGravity.x;
	var accelerationY = event.accelerationIncludingGravity.y;
	var accelerationZ = event.accelerationIncludingGravity.z;
}

Demo

Online Demo (require Safari Mobile)

API

DeviceMotionEvent Class
DeviceOrientationEvent Class

This entry was posted in Ipad, Iphone, Javascript and tagged , , , , . Bookmark the permalink.

8 Responses to Javascript Accelerometer Demo and Source

  1. social workers says:

    this post is very usefull thx!

  2. Excellent. I’m using this in my upcoming website: http://www.progettystudio.com

  3. That is very fascinating, You’re a very professional blogger. I’ve joined your feed and look forward to looking for extra of your excellent post. Also, I’ve shared your website in my social networks

  4. Ian Gilman says:

    Great info! I believe it should be event.acceleration rather than event.accelerationGravity, though.

  5. Pete Smith says:

    Hi,

    This is great… but have you experienced reverse gravity if you have the iPad rotated a certain way on load?

    The address bar is at the top but the gravity is reversed.

    Is there a way of detecting this / reversing the calculations?

    Cheers

    Pete

  6. Alberto says:

    Hi Pete,
    to check che orientation of the iPad (ex: portrait upside-down) you can use the window.orientation property.
    You can also use the orientationchange event to trigger some action when orientation change:

    window.addEventListener(‘orientationchange’, updateOrientation, false);
    function updateOrientation() {
    var orientation = window.orientation;
    switch (orientation) {
    // case …
    }
    }

  7. Michael says:

    Why am i sooo noob… I would like to have a script that will scroll my website in mobile style using the accelerometer.

    It seems that i don’t have the knowledge to write it myself. Could somebody help me to do it?

    Thank you in advance

  8. raslanove says:

    Thank you very much, this is very helpful :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>