HTML5 has a several API’s that are designed to use with mobile devices because more and more smartphones are used to access websites. Moreover, it is predicted that smartphones and tablets are going to surpass desktop computers accessing the web in the near future.  So, the HTML5 Vibration API is one those API’s that are going to be very useful on responsive web applications where developers can use features of the device to improve the user experience.

Support by Feature Detection

In order to verify if the API is supported by the browser, it is necessary to use feature detection in the navigator object.

if(navigator.vibrate){

//Execute this code only if it is supported.

}

Vibrating for One Second

The vibrate method takes a single integer, which represents the milliseconds that the vibration is going to keep running. So, we need to pass 1000 as parameter to execute the vibration for one second.

navigator.vibrate(1000);

Alternatively, you can pass an array with one element, and it would work.

navigator.vibrate([1000]);

Vibrate More Than Once

You already saw that it is allowed to pass an array to the vibrate method. But, in the previous example we passed an array with one single element.  If the array has multiple elements, the first element is going to be the duration of the vibration and the second one is going to be the delay for the next vibration. The following code runs the vibration for 2 seconds, then stops for 1 second, and runs again for 3 seconds.

navigator.vibrate([2000, 1000, 3000]);

Cancelling the Vibration

If you want to cancel the vibration, it is necessary to pass a zero as the argument.

navigator.vibrate(0);

Conclusion

As we can see, the new HTML5 API’s are helping us to provide better user experiences no matter the device visiting the site. For example, for a desktop computer you may display a message on the screen while on smartphones, the message could be accompanied with a vibration of the device.

«
»