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 named 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 indexes and pause for values at odd indexes.
navigator.vibrate([320, 200, 320, 1000, 320, 200, 320]);
Here it will first vibrate for 320ms and pause for 200ms, then 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
- JavaScript Fetch API to make HTTP requests
- Play audio with HTMLAudioElement API in JavaScript
- The URLSearchParams API in JavaScript
- Understanding async and await in JavaScript
- A brief guide to Promises in JavaScript
Web Developer by Profession, Blogger by Passion.
JavaScript | React | Next | Angular | Vue | HTML | CSS