DEV Community

Cover image for The Vibration API in JavaScript
Amitav Mishra
Amitav Mishra

Posted on • Originally published at jscurious.com

The Vibration API in JavaScript

Vibrations are the best way to provide physical feedback to users for any action mostly for mobile users. For example, while showing a warning message or alert, while receiving a message or notification etc.

The Vibration API allows web apps to access the vibration hardware of the device (if exists) to create vibrations. It provides a method navigator.vibrate() for the same purpose.

The navigator.vibrate() method

This method takes a value of vibration duration in milliseconds and vibrates the device for that long.

navigator.vibrate(500); 
// device will vibrate for 500ms
Enter fullscreen mode Exit fullscreen mode

The Vibration API doesn’t support in few of the browsers like IE, Opera, Safari, etc., so it will be better to check the browser support before using it.

if (navigator.vibrate) {
   navigator.vibrate(500);
}
Enter fullscreen mode Exit fullscreen mode

Vibrating in a pattern

The vibrate() method can also accept an array of values as an argument. We can provide different values for how much time it will vibrate and how much time it won’t. It will vibrate for values at even index and pause for values at odd index.

navigator.vibrate([320, 200, 320, 1000, 320, 200, 320]);
Enter fullscreen mode Exit fullscreen mode

Here it will first vibrate for 320ms and pause for 200ms, then again vibrate for 320ms and pause for 1000ms, and so on.

To cancel a running vibration, we can call vibrate() method by passing 0 or an empty array as an argument.

navigator.vibrate(0);
// OR
navigator.vibrate([]);
Enter fullscreen mode Exit fullscreen mode

You may also like


Thanks for your time ❤️
Find more of my writings on web development at jscurious.com

Top comments (0)