10

How can I utilize the new MobileSafari device motion APIs to capture a "shake" event?

1 Answer 1

19

See this awesome blog post: http://www.jeffreyharrell.com/blog/2010/11/creating-a-shake-event-in-mobile-safari/

Which illustrates this example:

if (typeof window.DeviceMotionEvent != 'undefined') {
    // Shake sensitivity (a lower number is more)
    var sensitivity = 20;

    // Position variables
    var x1 = 0, y1 = 0, z1 = 0, x2 = 0, y2 = 0, z2 = 0;

    // Listen to motion events and update the position
    window.addEventListener('devicemotion', function (e) {
        x1 = e.accelerationIncludingGravity.x;
        y1 = e.accelerationIncludingGravity.y;
        z1 = e.accelerationIncludingGravity.z;
    }, false);

    // Periodically check the position and fire
    // if the change is greater than the sensitivity
    setInterval(function () {
        var change = Math.abs(x1-x2+y1-y2+z1-z2);

        if (change > sensitivity) {
            alert('Shake!');
        }

        // Update new position
        x2 = x1;
        y2 = y1;
        z2 = z1;
    }, 150);
}
6
  • 2
    Excellent. Thanks for adding the code extract. Should be helpful!
    – tbeseda
    Dec 17, 2010 at 22:33
  • 3
    Just a warning: accelerationIncludingGravity will never have all three components zero. If gravity is acting directly on one axis, that axis will have a value of 9.81. Also, why not check for shakes during the event instead of in an interval?
    – ughoavgfhw
    Dec 17, 2010 at 22:39
  • @Jacob Relkin I realised that on my iPhone 4S the alert occures TWICE after single shake. WHY?
    – andilabs
    Apr 10, 2013 at 10:27
  • @andi The only change I had was to get rid of the interval, instead putting the code in the event handler. Thinking now, that might not work as well since the change could appear slower if many events are used. As for double alerts: There is a change when you start shaking and when you stop, so you will get an alert for each.
    – ughoavgfhw
    Apr 10, 2013 at 17:38
  • 1
    The linked blog post has since been removed. Is it viewable somewhere else or is there a similar article I could read? May 13, 2013 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.