Triggering vibrations from your website

11 Dec, 2018

Most common mobile browsers (excluding safari) allow you to trigger the device's vibration motor from your web application using the Vibration API. The Vibration API is provided to you by the mobile browser itself, it allows for varying lengths of vibration to be specified, as well as letting you set vibration patterns to be followed in the form of an array.

Everything you need to start/stop and create vibration patterns can be accomplished with just the navigator.vibrate() function. It accepts either an integer representing milliseconds or an array of integers representing a vibration pattern.

Starting and stopping vibrations
Simply input the time in milliseconds you want the vibration to last. To stop the vibration, call the function with the value 0ms or an empty array.


//Vibrate for 1 second
navigator.vibrate(1000);

//Vibrate for 2 second
navigator.vibrate(2000);

//Stop vibrating
navigator.vibrate(0);
//or
navigator.vibrate([]);
		

Creating vibration patterns
This is done using an array with alternating values for "vibration length" and "wait length". The best way to understand is to see the code.


// Vibrate for one second, wait for half a second, then vibrate for two second
navigator.vibrate([1000, 500, 2000]);

//The pattern can be as long as you desire
navigator.vibrate([500, 200, 1000, 500, 1000]);
		

If you're reading this on your phone (provided it has a vibration motor and you aren't on safari) you should be able to tap the button in the CodePen below and experience the vibration API in action.

See the Pen Triggering vibrations from your website by Karna Malone (@kknmalone) on CodePen.

There are quite a few potential applications for this API. For example, haptic feedback in a web-based game, or alerting the user to notifications in a web app just to name a few. Whatever you use it for, always to remember to keep the user's experience in mind so you don't irritate them away from your site.


Other Tutorials

View All

Local Storage vs Cookies (The storage showdown)

javascript


Local site storage can open up a ton of possibilities in web design and breath new life into an otherwise static web page. Whether you want to do something simple like "show a welcome message only once", or something more complex.

Building a custom chromecast web app

html - javascript


Chromecasts make streaming your favourite songs, games and movies easy. But if you're like me, you might be wondering what's going on behind the scenes when you cast an app, and how you can build your own.

Handy Python tricks for beginners

python


When first starting out in a language like Python, things tend to move a bit slow until you learn how to use the built-in functions and operators which exist to speed up the development process. So this tutorial will try to mitigate that problem.