Thursday, 11 August 2016

Vibrate Mobile Device Using HTML5

HTML5 provide different sets on API like Camera, Geo Location, Battery and many more APIs. Vibrate api is one if them. Today every mobile vendor provide vibrating functionality in its device.

We can implements vibrate functionality with two type. First is to use native api, like Android, IPhone, Blackberry its own sets of native api for vibrating functionality. But there is drawback of this. You need to learn its native language like Java, Objective-c or Swift to implements this.

Here are the implementation of Native implementation of vibrate mobile device.




Second method is to use HTML5 API. Which is platform independent. So in this tutorial we use HTML5 API to implement this functionality. HTML5 API runs only in browser either it is Mobile browser or Desktop Browser. You need that Browser which support HTML5 APIs.


Vibrate does not work in Desktop/Laptop Browser because there is not hardware for vibration in desktop/laptop.


Browser Support of Vibrate API

Before we use the api , we need check whether vibrating functionality is supported by browser or not. Then we use  vibrating functionality.

if ("vibrate" in navigator) {
// vibration API supported
}


To check and use prefixed versions, you can use code such as:


navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;
if (navigator.vibrate) {
// vibration API supported
}


Implement Vibrate functionality

Vibration is set by passing milliseconds in vibrate method. Then device vibrate upto that value which is passed in vibrate method. For ex. 1000 milli seconds, device will vibrate for 1 second.


navigator.vibrate(1000);

Vibrate method also accept array of vibration and delay time(milliseconds)

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

The above code vibrate for 1000ms , the wait for 500ms and then vibrate again for 1000ms. You can any number of arguments in an array.

No comments:

Post a Comment