Vibrating Mobile Devices with Javascript

The Vibration API makes it possible for a web application to vibrate a mobile device with Javascript. There will be no effect on devices that don't have vibration hardware present.

Vibrating a mobile device has some special use-cases — passing alerts or notifications to the user, or shaking effect while playing a game.

Demo

Starting the Vibration

The device can be vibrated using the navigator.vibrate() method.

  • Single vibration : To perform a single vibration, an integer can be passed as the parameter. This represents the time in milliseconds for which device will vibrate.

    // vibrate device for 300 milliseconds
    window.navigator.vibrate(300);
    
  • Multiple vibrations : To perform multiple vibration, an array needs to be passed as the parameter. First value represents vibration time (milliseconds), second value represents pause time (milliseconds), third value represents vibration time, and this goes on with each alternate value. Basically it is performed as a series of [VIBRATION] [PAUSE] [VIBRATION] [PAUSE] [VIBRATION] [PAUSE]...

    // vibrate for 300 milliseconds
    // then wait for 100 milliseconds
    // vibrate again for 200 milliseconds
    // wait for 50 milliseconds
    // vibrate again for 300 milliseconds
    window.navigator.vibrate([300, 100, 200, 50, 300]);
    

Return value of navigator.vibrate() : a boolean false will be returned if the parameter given was invalid, and true otherwise.

Note that return value of true does not indicate that vibration successfully happened. It just indicates that parameter given was valid syntactically. In desktop browsers where there is no vibration hardware, this will still return a true.

Cancelling an Ongoing Vibration

Passing 0 as parameter to navigator.vibrate() will cancel out the vibration.

// cancel out ongoing vibration
window.navigator.vibrate(0);

Other Things to Note

  • If the device does not have a vibration hardware, nothing will happen. Neither it is possible to know that vibration did not happen there.
  • If a vibration is already in progress, and a second vibration call is made, then the first one is stopped and the second vibration pattern begins.
  • If the length of the vibration is too long — then browser will consider entries till the allowed length (set by the browser), and truncate the rest.