Bibek's Blog

Bibek's Blog

How To Use Vibration API In Your Website

Haptic Feedback in Your Website

How To Use Vibration API In Your Website

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Hello everyone 👋

In this article, we will see how can we use Vibration API in our websites.

We can use the Vibration API to provide haptic or vibration feedback to the user using the website for their actions.

Most modern mobile devices include vibration hardware, which lets software code provide physical feedback to the user by causing the device to shake. So this API works well with mobile devices only and targeted for the same.

The Vibration API allows the web apps to access the vibration hardware if it exists.

Implementation 👨‍💻

Let's explore the API.

We can access the API from the browser's window.navigator object.

Check Vibration API Support

It is always a good idea to check for API support.

if (Boolean(window.navigator.vibrate)) {
    // It Supports
    ...
}
  • vibrate is a method that is responsible for the vibration.
  • It expects one argument.

Argument is a number or an array of numbers for a series of vibrations. Those numbers are considered as milliseconds.

If the method was unable to vibrate because of invalid parameters, it will return false else it returns true.

Single Vibration 📳

For a single vibration, we can pass a single number directly or in an array.

// Will vibrate the device for 500ms
window.navigator.vibrate(500);

// Same as the above line
window.navigator.vibrate([500]);

Pattern Vibration 📳 📳 📳

To vibrate the device in a pattern, we can pass an array of numbers.

Even indices numbers are responsible for the vibration and odd indices numbers will delay that much millisecond before the next vibration.

// Vibrate for 500ms, Wait for 200ms, Vibrate for 800ms
window.navigator.vibrate([500, 200, 800]);

Cancelling Vibrations

To cancel an ongoing vibration pattern, we need to pass a 0 or an empty array or an array containing all zeroes to the vibrate method.

window.navigator.vibrate(0);
window.navigator.vibrate([])

Fun Example ✨

Vibrate SOS in morse code.

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

Working only on Chrome Android.

Sample Code | Live Link


Thank you for reading 🙏

If you enjoyed this article or found it helpful, give it a thumbs-up 👍

Feel free to connect 👋

Twitter | Instagram | LinkedIn

Interested in reading more such articles from Bibek Kakati?

Support the author by donating an amount of your choice.

Recent sponsors