The Vibration API in JavaScript.
JavaScript developer

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 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 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([]);        

Try out these powerful codes and see them in action (Try this on a mobile device).


?? Attention! ??


If you find any errors in the computer code or grammar, broken links while reading this article, please let me know. I apologize in advance for any inconvenience caused.



要查看或添加评论,请登录

Denis Rylikov的更多文章

社区洞察