How to use the Vibration API

Since the arrival of HTML5 and with it the increasing number of applications built for mobile, more and more JavaScript APIs have surfaced to meet the demand; one of these APIs is the Vibration API.

As the name suggests, the Vibration API allows you to control the vibration of a device, by setting it to vibrate for a certain length of time, or within a pre-defined pattern.

Browser support

Firstly, this is a mobile technology. Don’t try and make your iMac vibrate, it won’t work.

For mobile browsers, the support is fair: no support yet in IE or Safari; on Android the native browser, Chrome and Firefox all support it; Chrome on iOS doesn’t yet support it.

The important thing to note is that vibrations tend to be used as notifications, so using this API is a progressive enhancement. As such, it is usable now.

Using the API

The first thing you should do when using this type of API is test for browser support:

if (window.navigator && window.navigator.vibrate) {
   // Vibration API is supported
} else {
   // Not supported
}

Now, inside the if statement we can call the vibrate function, and make the user’s mobile device vibrate for 500 milliseconds:

navigator.vibrate(500);

As you can see, this API is pretty straightforward to use. If you want to add a vibration to alert the user to an event in your app, this is all you need…

…but as you might expect, we can also get much more creative.

Let’s say you want to add a specific type of vibration for a particular action which makes the device vibrate twice, first for 500ms and the pause for 200ms followed by a vibration lasting 1 second. We’d code that like so:

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

All we’ve really done is add an array instead of a single number. (I’ve used two sets in the example, but you can use as many as you like.)

Let’s say you want to cancel a vibration that’s going on, that is as simple as setting a new vibration with a duration of zero, like so:

$('.stop').click(function() {
    navigator.vibrate(0);
}); 

or:

 $('.stop').click(function() {
    navigator.vibrate([]);
}); 

Conclusion

These kinds of API have been surfacing regularly over the last year, and they make life a lot easier when coding for mobile.

The Vibrate API allows you to give your user not just visual, but tactile feedback, which is hugely beneficial when communicating on a small screen.

Sara Vieira is a freelance Web Designer and Developer with a passion for HTML5/CSS3 and jQuery. You can follow her on twitter or check out her website. More articles by Sara Vieira
Home CSS Deals HTML HTML5 Java JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress