Skip to content

Instantly share code, notes, and snippets.

@aidanbon
Created January 12, 2014 05:09
Show Gist options
  • Save aidanbon/8381182 to your computer and use it in GitHub Desktop.
Save aidanbon/8381182 to your computer and use it in GitHub Desktop.
shake.js - Enable shake gesture detection to trigger a callback function. Code based on a gist by iLee @ https://gist.github.com/leecrossley/4078996
/*
* shake.js - Enable shake gesture detection to trigger a callback function.
* Code based on a gist by iLee @ https://gist.github.com/leecrossley/4078996
*
* Sample usage:
* var Shaker = require("./shake");
* var shaker = new Shaker(
* function onShakeSuccess() {
* console.debug("Shake motion detected!");
* },
* function onShakeError() {
* console.debug("Shake error");
* });
*
* if (shaker.isShakable()) {
* shaker.startWatch();
* }
*/
var Shake = module.exports = function (successCB, errorCB, options) {
this.optons = options || { frequency: 100 };
this.shakeCallBack = successCB;
this.errorCallBack = errorCB;
this.lastVal = { x: null, y: null, z: null };
};
var withThis = function withThis(context, fn) {
return function() {
return fn.apply(context, arguments);
};
};
// Check if accelerometer is supported
Shake.prototype.isShakable = function() {
return navigator.accelerometer;
};
// Start watching the accelerometer for a shake gesture
Shake.prototype.startWatch = function () {
if (!this.isShakable()) {
return;
}
this.watchId = navigator.accelerometer.watchAcceleration(withThis(this,
this.assessCurrentAcceleration), this.errorCallBack, { frequency: 300 });
};
// Stop watching the accelerometer for a shake gesture
Shake.prototype.stopWatch = function () {
if (!this.isShakable()) {
return;
}
if (this.watchId) {
navigator.accelerometer.clearWatch(this.watchId);
this.watchId = undefined;
}
};
// Assess the current currVal parameters to determine a shake
Shake.prototype.assessCurrentAcceleration = function (currVal) {
var delta = {x:0, y:0, z:0};
if (this.lastVal.x !== null) {
delta.x = Number(Math.abs(this.lastVal.x - currVal.x));
delta.y = Number(Math.abs(this.lastVal.y - currVal.y));
delta.z = Number(Math.abs(this.lastVal.z - currVal.z));
}
var deltaTotal = delta.x + delta.y + delta.z;
if (deltaTotal > 10) {
// Shake detected
if (typeof (this.shakeCallBack) === "function") {
this.shakeCallBack();
}
this.stopWatch();
setTimeout(withThis(this, this.startWatch), 1000, withThis(this, this.shakeCallBack));
this.lastVal = { x: null, y: null, z: null };
} else {
this.lastVal = {x: currVal.x, y: currVal.y, z: currVal.z};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment