Vibration API in HTML5

Vibration is a simple, a nice way of alert when you get a new message or a phone call. It is especially useful when you are in a noisy environment or the place where you feel the ringing would be a distraction for others.

It is comforting to know that HTML5 is now providing us to play with the vibration on devices. But the HTML5 Vibrate API supports only the recent version of Firefox & Chrome.

To check the vibration API support in browsers,

navigator.vibrate = navigator.vibrate || navigator.mozVibrate ||

navigator.webkitVibrate || navigator.msVibrate;

if (navigator.vibrate) {
// supports vibration API.
}

Vibration Syntax

Vibration basic syntax is,

    navigator.vibrate(long | [long]);

The vibrate function accepts milliseconds or array of milliseconds.

Example 1

// vibrate for 1000 ms
navigator.vibrate(1000);
// same like above but in array of ms
navigator.vibrate([1000]);

In the above examples, we are setting the device to vibrate 1000 milliseconds.

Example 2

// passing array of milliseconds
navigator.vibrate([50, 100, 150]);

As we know, the vibrate function accepts array of longs [milliseconds]. Here in the array, The ODD indexed numbers means the delay for the vibration.

In the above given example, the device will vibrate for 50 milliseconds initially and wait for 100 milliseconds then again it will vibrate for 150 milliseconds.

Cancelling Vibration

To cancel the vibration, just pass 0 or empty array [] as shown below.

// cancel any existing vibrations, pass 0 navigator.vibrate(0); // or pass empty array navigator.vibrate([]);

As vibration is non-blocking core function, your other scripts can run simultaneously without any script block.

JSFIDDLE

The above link has the script to check the vibration on devices.

Source: w3schools
Ebook Download
View all
Learn
View all