The HTML5 Vibrate API

The HTML5 Vibrate API allows you to trigger vibration on a device.

Make me vibrate

Mobile and tablet devices have become hugely prevalent in how users access the web. So much so that Walmart reported that on Black Friday over 50% of traffic was via mobile traffic. This is good news for developers as these devices come with a range of capabilities that are largely accessible through HTML5. You can get access to the camera and audio on these devices and you can also trigger vibration on a device.

The HTML5 Vibration API is a W3C Candidate Recommendation and as such browser vendors are using vendor prefixes. We can normalise this easily though.

navigator.vibrate =
  navigator.vibrate ||
  navigator.webkitVibrate ||
  navigator.mozVibrate ||
  navigator.msVibrate;

You can check for browser support like this

navigator.vibrate =
  navigator.vibrate ||
  navigator.webkitVibrate ||
  navigator.mozVibrate ||
  navigator.msVibrate;

if (navigator.vibrate) {
  console.log("we can vibrate");
} else {
  console.log("no vibration for you :-(");
}

Usage

To make a device vibrate is a simple as

navigator.vibrate(500);

The number value is the time in milliseconds that the device should vibrate for.

You can also trigger a number of vibrations by passing an array. Every second value represents the delay before the next vibration in the array should be triggered.

navigator.vibrate([1000, 1000, 500]);

In the above example the device will vibrate for a second, wait for a second and then vibrate for half a second.

To stop vibration immediately you can do this.

navigator.vibrate(0);

Browser support

I wasn’t able to find any good documentation on browser support for the HTML5 Vibrate API so I knocked up a quick test and ran it against my mobile and tablet devices.

At the time of writing the following are supported

At the time of writing the following are unsupported

Now you know how to go and create your dildonics startup.

References

Tags

Can you help make this article better? You can edit it here and send me a pull request.

See Also