Introduction to the Vibration API

Spread the love

As the differences between native apps and web apps slowly disappear, web developers get access to more hardware, one of which is the vibration motor.

The Vibration API is used to vibrate the device, the API allows you to vibrate the device once or in a pattern. If you try out the API on a device which does not have vibration hardware, the call to the api simply returns true and does nothing else.

Single Vibration

To vibrate the device for one time, simply call the navigator.vibrate function and pass in the time in milliseconds to vibrate the device

navigator.vibrate(1000) //Vibrate the device for 1 second

Pattern Vibration

The API also allows you to vibrate the device in a pattern, to do this you need to pass an array to the api where for each odd indexed item the API will vibrate and for each even indexed item the API will wait.

Example: 
navigator.vibrate([100,200,100,200,100] //vibrate for 100ms then wait for 200ms then vibrate for 100ms and so on..

Stop Vibration

To stop any ongoing vibration, simply call the vibrate method passing in nothing or 0

navigator.vibrate(0) //Stop any existing vibration
navigator.vibrate() //Stop any existing vibration

Support

Most mobile browsers support the Vibration API, you can find the full list here.