How can I utilize the new MobileSafari device motion APIs to capture a "shake" event?
1 Answer
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);
}
-
2
-
3Just 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? Dec 17, 2010 at 22:39
-
@Jacob Relkin I realised that on my iPhone 4S the alert occures TWICE after single shake. WHY?– andilabsApr 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. Apr 10, 2013 at 17:38
-
1The 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