1 min read

Vibration API

The Vibration API allows web applications to provide tactile feedback to the user by vibrating the device. This is particularly useful for mobile web apps, games, or notifications.

1. Basic Usage

The API is accessed through the navigator.vibrate() method.

Single Vibration

To vibrate the device for a specific duration (in milliseconds):

// Vibrate for 200ms
navigator.vibrate(200);

Vibration Patterns

You can create patterns by passing an array of numbers. The values alternate between vibration duration and pause duration.

// Vibrate for 500ms
// Pause for 200ms
// Vibrate for 500ms
navigator.vibrate([500, 200, 500]);

2. Stopping Vibration

To stop any currently running vibration, you can pass 0 or an empty array.

navigator.vibrate(0);
// or
navigator.vibrate([]);

3. Limitations and Requirements

  • Hardware: Obviously, this only works on devices with vibration hardware (mostly smartphones and tablets). On desktops, it usually does nothing (returns false).
  • User Interaction: To prevent abuse (like annoying ads vibrating your phone), modern browsers often require a user gesture (like a click or tap) before navigator.vibrate() will work.
  • Visibility: Vibration is automatically stopped when the user switches tabs or minimizes the browser.

4. Checking Support

if ("vibrate" in navigator) {
  // Vibration API is supported
  navigator.vibrate(200);
}

programming/javascript/vanilla/javascript programming/javascript/vanilla/notifications-api