Vibrate A Cell Phone In Javascript

Introduction

Nowadays, almost every website has its own Android/iOS app, so sometimes there is a requirement to vibrate the cellphone on a particular event. Someone has a need to vibrate the cellphone as their tech stack is javascript, so they simply use the Vibration API for that.

Vibration API 

Vibration is a way to provide physical feedback to users for a particular event. Suppose a user is submitting a form and there is a warning or an error. So in this case, we can send physical feedback to the user, or one of the common use cases these days is receiving a notification or message.

Vibration API is a Javascript API that allows web pages to respond to the event with a vibration mechanism if the device supports it. This feature is supported by modern mobile browsers and some web browsers, mainly chrome, and firefox.

It provides the navigator.vibrate() method for the same purpose. This method takes a value of Vibration duration in milliseconds and vibrates the device for that time.

navigator.vibrate(1000); 
// device will vibrate for 1000ms/1s

It's better to check the browser compatibility first before using this API so that we can avoid the exceptions where this API is not supported. For that use the below piece of code.

if (navigator.vibrate) {
   navigator.vibrate(1000);
}

Vibration in a pattern

It is also possible to vibrate the device in some pattern for which we have to give the array of values as an argument. It will vibrate for values at an even index and pause for values at the odd index. The value defines how much time it will vibrate and how much time it wouldn't.

navigator.vibrate([740, 100, 520, 200]);

First, it will vibrate for 740ms and wait for 100ms and then again vibrate for 520ms and goes on like this.

Cancel the Vibration

To cancel the running vibration, we can call the vibrate method with 0 as an argument. It will cancel the vibration.

navigator.vibrate(0);

Example

 <button onclick="vibrate()"> Vibrate Me </button>
<script>
  function vibrate() {
    if (navigator.vibrate) {
      navigator.vibrate(1000);
    }
    else {
      console.log("Vibration API is not supported");
    }
  }
</script>

Conclusion

On the Button click, it will vibrate for 1 second if the vibration API is supported on the device browser. Else it will not vibrate, and neither it give any error if that browser does not support the API.

Note - Make sure to use this API sensibility. It may annoy users if it is overused. 

Please let me know some more use cases in the comments where we can use this Vibration API, Happy Coding :)