The Vibration API in JavaScript
Amitav Mishra
Posted on October 19, 2022
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
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);
}
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]);
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([]);
You may also like
- Send push notifications with the Notification API in JavaScript
- Play audio with HTMLAudioElement API in JavaScript
- The URLSearchParams API in JavaScript
- JavaScript Fetch API to make HTTP requests
- Map in JavaScript and when it's a better choice than Object
- JavaScript Set object to store unique values
- Generator functions in JavaScript
- A brief guide to Object.defineProperty() method
- A brief guide to Promises in JavaScript
- 20+ JavaScript shorthand coding tricks
Thanks for your time ❤️
Find more of my writings on web development at jscurious.com
Posted on October 19, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 10, 2023