Vibrating Mobile Devices with Javascript

Use-Cases of this Tutorial

  • Know how to vibrate a mobile device using native Javascript methods.
  • Know about the navigator.vibrate() method.

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.


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
  • 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.

See also  Pure CSS / CSS3 Fullscreen Hamburger Menu

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 as parameter to navigator.vibrate() will cancel out the vibration.

// cancel out ongoing vibration

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.
See also  Reducing Array Values to a Single Value in Javascript

Leave a Reply

Your email address will not be published. Required fields are marked *