The Vibration API makes a device vibrate, providing some haptic feedback for your users. This API actually used to be called the Vibrator API, but I’m sure you don’t need me to tell you why that name was changed very quickly. Obviously not all devices are capable of vibrating, especially larger ones, so this API is decidedly more useful in mobile devices.
The API is extremely simple, requiring only the vibrate() method on the navigator object. The value supplied to vibrate() is a figure representing the number of milliseconds for the device to vibrate; for example, to make the device vibrate for one-fifth of a second after the user has completed a touchend event, use this code:
document.addEventListener('touchend', function () {
window.navigator.vibrate(200);
});
You can also use an array of values that alternate between vibrations and pauses; that is, the odd-numbered values are vibrations and the even values are pauses. In this example, the device vibrates for 200ms, pauses for 200ms, and then vibrates for 500ms:
document.addEventListener('touchend', function () {
window.navigator.vibrate([200,200,500]);
});
Vibrating runs down the battery more quickly, so use this API with caution. You can manually stop a vibration by using a 0 or an empty array value. In this code, the device will begin to vibrate for 5 seconds when the touch event starts, and then stops when the event ends:
document.addEventListener('touchstart', function () {
window.navigator.vibrate(5000);
});
document.addEventListener('touchend', function () {
window.navigator.vibrate(0);
});
You can try the API for yourself in the example file vibration.html, even though obviously you’ll need to open it on a mobile device with vibration capabilities if you want to actually feel the vibrations. If you don’t have one on hand, Figure 6-5 shows a reconstruction of the experience.