Vibration Web API

Vibration Web API

Simple Implementation

Vibration Web API is the API to control vibration on the device. Currently (May 18th 2021), this API is not supported on IOS devices. Also it will not work if your device doesn't have vibration mechanism although it supports API.

Thanks to @bibekkakati for his blog which gave me inspiration to try out his project.

Demo | Code

That's being said, lets see what we have done here,

First, its a good idea to check if the device supports the API or not by doing.

// Check if the device supports the Vibration API
const support = Boolean(window.navigator.vibrate);

This will set the value of support to true or false depending upon whether the device supports the vibration API or not. Since we have the status, now we can display the status if we want like,

    console.log('Vibration API is supported.');
    //Any other logics.
    console.error('Vibration API is not supported.');
    //Any other logics.

Here's the simple html code with a button to trigger the vibration.

Note: Modern browsers do not trigger the events on pageload until first user action on the page.

Chrome error image

So we are using a button to trigger an event here.

Here's the html

    <button id="btn">Vibrate</button>

Lets grab that button with id btn from js.

const btn = document.queryselector('#btn');
        //Your vibration logic.

Now for vibration logic, window.navigator.vibrate method is responsible with accepts an array with multiple values.

  • For static vibration

    If we provide single valued array, then it will vibrate for provided interval and then stops.


    In this example, device will vibrate for 500ms and then stops.

  • For vibration pattern

    We can also provide multiple values to the array starting with 0, even index values are the time for vibration and odd index values are for interval between vibration.


    In this example, device will vibrate for 500ms waits 250ms , again vibrates 500ms and waits 250ms and so on. This flexibility allows us to program different vibration patterns. Here are some sample vibration patterns.

//Older Iphone Vibration pattern.

//Legacy samsung phone's vibration pattern.

// Morse code for SOS
  • Stop the Vibration
    To stop the vibration for any reason, we can pass an empty array to the method and the vibration will stop.

That's it. Happy coding.