Shake Gesture Detection in PhoneGap

Detecting shake events in your PhoneGap / Cordova apps

Last year I wrote a cross-platform app for a client (iOS and Android), where a last minute requirement was added to randomise something on the screen when the mobile device was shaken.

I was a bit worried at first, as there weren’t any core or 3rd party plugins to do this out of the box. Then I realised, it must be pretty easy to do with the device accelerometer.

The gist

I wrote a shake.js gist 10 months ago, which uses the navigator.accelerometer to watch and get the devices acceleration. It took quite a while to tweak the variables to get it just right but testing on real iPhone and Android devices helped my trial and error.

The gist has quite a few stargazers, forks and comments and is about to be mentioned by a published tech author in his latest book. All of this past me by until recently, as I don’t generally monitor my gists :)

Using shake.js

If you’re interested in using shake.js, it’s pretty simple. It’s not documented on the gist but is pretty self explanatory to any JavaScript developer:

shake.js usage
var onShake = function () {
// Code fired when a shake is detected
// Start watching for shake gestures and call "onShake"
// Stop watching for shake gestures


Even though I’ve only used this on iPhone and Android, in theory it should work on Windows Phone and BlackBerry too, provided the hardware supports it.

Don’t be an Outkast - Shake it, shake, shake it, shake it (oh oh).