HTML5: Vibration API

The API for telling a device to vibrate from within the browser is very new and not well supported. Can I Use does not have a listing for it and, as of this writing, support is limited to Android and Firefox mobile platforms. Browsers on iOS do not implement it and, although most Chrome versions regardless of platform include the method itself, the functionality itself is tied only to platforms like Android that allow it.

However, for those who wish to use the API, I suggest looking at the W3C Candidate Recommendation and the Mozilla Developers Network page (from which my own code comes) for information on some suggested user cases. I also advise curtailing constant usage in projects as some users my find it troubling or a drain on battery usage on mobile devices. Use with caution and respect for the user.

/**
* A Vibrate object for detecting and using the window.navigator.vibrate
* function.
*
* Code borrows from David Walsh's work
* http://davidwalsh.name/vibration-api
*
* @property {boolean} supported If vibrate is supported in the current context
*/
var Vibrate = (function(self) {
self.supported = ('vibrate' in window.navigator);
var interval = null;
/*
* Starts vibration for given duration
* @param duration Amount of time in ms to vibrate
*/
self.startVibrate = function(duration) {
if (self.supported) {
window.navigator.vibrate(duration);
}
};
/*
* Clears the interval, if set, and stops any current vibration
*/
self.stopVibrate = function() {
if (self.supported) {
if (interval !== null) {
clearInterval(interval);
}
window.navigator.vibrate(0);
}
};
/*
* Starts a peristent vibration for the given duration and interval
* @param duration The amount of time to vibrate in ms
* @param interval The amount of timne to pause between vibrations in ms
*/
self.startPeristentVibrate = function(duration, interval) {
interval = window.setInterval(function() {
startVibrate(duration);
}, interval);
};
return self;
})(Vibrate || {});
view raw vibrate.js hosted with ❤ by GitHub