Vibration API using Native JavaScript

Vibration API in JavaScript

Vibration API is a part of the Web Platform and comes along with most of the Web Browser. The Navigator.vibrate() method is a part of most of the modern browsers and it gives you a direct access to the Vibration Hardware. This can really make a great effect in use cases when you have an alert of a message where you want your user to respond for sure.

This works if the device has the appropriate hardware. You can setup patterns in the device to turn it on or off at your will and the pattern will take effect. If at any instance when one pattern is in progress and someone triggers it again the previous pattern will halt and a new will begin.

Code Implementation for Vibration API

Code wise implementation is as follows:-

For Single Vibration

window.navigator.vibrate(10000);

The above one line code can vibrate your device for 10seconds. This is a simple one. Let’s see the pattern.

For Vibration Pattern

In order to have a specific vibration pattern, your only choice will be to go ahead and change the single value to an Array. That’s it. So the code will be as shown below.

window.navigator.vibrate([200, 100, 200,200, 100, 200,200, 100, 200,200, 100, 200,200, 100, 200,200, 100, 200,200, 100, 200,200, 100, 200,200, 100, 200,200, 100, 200,]);

To sum this up you guys can open this example on your mobile/tab browser and this will work fine

HTML Code

<button onclick="vibrateOnce()">Vibrate Once</button>
<button onclick="stepVibration()">Step Vibration</button>

JavaScript Code

function vibrateOnce(){
window.navigator.vibrate(10000);
}
function stepVibration(){
window.navigator.vibrate([200, 100, 200,200, 100, 200,200, 100, 200,200, 100, 200,200, 100, 200,200, 100, 200,200, 100, 200,200, 100, 200,200, 100, 200,200, 100, 200,]);
}

You can alternatively have a look at the embedded JSFiddle.

This was it. See how easy it is to integrate the Vibration API into your application.

Please go ahead and check out the other Tutorials on JavaScript Device API or the Web Platform.

Originally published at The Web Juice.