Advertisement
Scroll to top

HTML5 has been a breath of fresh air for the web, which hasn't only affected the web as we know it. HTML5 provides a number of APIs that enable developers to create interactive websites and improve the user experience on mobile devices. In this article, we'll take a closer look at the Vibration API.

Do you remember when the PlayStation was first introduced in the nineties? If you do, then you may also remember that a small revolution was created with the introduction of the DualShock, a controller that introduced feedback by means of vibration. It was a tremendous success.

All my friends with a PlayStation console switch to the DualShock almost immediately and I was no exception. Why was it so successful? The key factor of its success was its ability to provide feedback to the player in the form of vibration, it made you feel more connected with the game as if you were in the game.

The DualShock was just the start of this trend. Controllers have become much more advanced with the Kinect and revolutionary products, such as the Oculus Rift and the incredibly popular Omni.

The web has become much more powerful and the result is that game development has moved to the web. Until a few years ago, games for the web relied on Flash and Silverlight. Today, however, these technologies are no longer needed to develop games for the web and this is largely due to HTML5.

With increased power comes increased responsibility. For the web, this means the need for well-defined APIs that help create a better user experience and the ability to take advantage of new technologies available on, for example, mobile devices. One such API is the Vibration API.


1. What is the Vibration API?

The Vibration API was designed to address use cases in which tactile feedback is necessary or desired. Virtually every modern, mobile device includes has the ability to vibrate. The Vibration API offers the ability to programmatically access the device's vibration capabilities and work with them. The API isn't meant to be used as a generic notification mechanism as the Web Notifications API was created for this exact purpose. Even though the Vibration API is a W3C Candidate Recommendation at the moment, the specifications hasn't changed for several months, which is an indication that the specification to reach the final stage, the W3C Recommendation, shortly.

As with native mobile applications, the possibilities of the Vibration API are endless. You can use it while playing a video so that the device vibrates on explosions. Games are another excellent fit for the Vibration API. Games already make extensive use of the hardware capabilities of mobile devices and the Vibration API is therefore a great fit for web games. Just remember why the DualShock became so popular and you'll understand what I mean.


2. Implementation

Now that we know what the Vibration API can do for us, let's see how we can use it. Let me start with some good news, the API is very easy to use–almost trivial. There's only one method you need to know about, vibrate. That's it. The vibrate method belongs to the window's navigator. The vibrate method accepts one parameter, which can be an integer or an array of integers.

If a single integer is passed to the vibrate method, the device vibrates for the duration of the integer in milliseconds. If you pass an array of numbers, a vibration pattern is defined. The integers at odd indexes tell the device how long to vibrate while the integers add even indexes indicate how long the pauses between the vibrations should be. To stop the device from vibrating, you can pass 0 to vibrate or invoke the method without any parameters.

An image is worth a thousand words, but, for developers, a code snippet is probably worth a billion words. Let's explore a few examples.

Step 1: Detecting Support

To detect whether the device's browser supports the vibration API, you can perform a simple check as shown below.

1
if (window.navigator && window.navigator.vibrate) {
2
   // Shake that device!

3
} else {
4
   // Not supported

5
}

Another option is to inspect the navigator object.

1
if ('vibrate' in navigator) {
2
   // Shake that device!

3
} else {
4
   // Not supported

5
}

Step 2: Vibrate Once

To tell the device to vibrate, we invoke the vibrate method and pass it an integer. For example, to tell the device to vibrate for one second we would do the following:

1
// Vibrate once for 1 second

2
navigator.vibrate(1000);

Step 3: Vibrate Multiple Times

To tell the device to vibrate several times with a pause between each vibration, we pass an array of integers to the vibrate method. If we want the device to vibrate twice with a pause of half a second and end with a vibration of two seconds, we would do the following:

1
// Vibrate three times

2
// First two vibrations last one second

3
// Last vibration lasts two seconds

4
// Pauses are half a second

5
navigator.vibrate([1000, 500, 1000, 500, 2000]);

Step 4: End Vibration

To stop the device from vibrating, we pass the vibrate method 0 or an empty array.

1
// Stop vibrating

2
navigator.vibrate(0);

Or:

1
// Stop vibrating

2
navigator.vibrate([]);

Browser Support

Support for the Vibration API is fairly good in desktop and mobile browsers. The major browsers that currently lack support for the API are Internet Explorer and Safari. Take a look at this summary to get an idea of which browsers support the API.

  • Firefox 11+: Prior to version 15, you need to use the -moz prefix.
  • Opera 17+: To use it in versions prior to 19, you need to activate the flag "Experimental Web Platform features".
  • Chrome 30+: To use it in versions prior to 32, you need to activate the flag "Experimental Web Platform features".

A real polyfill for the Vibration API doesn't exist. However, there is a polyfill that targets Firefox OS. It was created by Christian Heilmann and it's called mozVibrate-polyfill. You can find it on GitHub.


Demo

I'd like to end this tutorial with a simple demonstration of the Vibration API. It's a simple HTML5 page that contains three buttons, one to vibrate once, one to vibrate repeatedly, and a button to stop vibrating. The demo detects if the browser supports the API. It it doesn't, you'll see the message "API not supported" and the buttons are disabled. I recommend testing the demo on a mobile device.

1
<!DOCTYPE html>
2
<html>
3
   <head>
4
    <meta charset="UTF-8">
5
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
6
    <meta name="author" content="Aurelio De Rosa">
7
    <title>Vibration API Demo by Aurelio De Rosa</title>
8
    <style>
9
      body
10
      {
11
          max-width: 500px;
12
          margin: 2em auto;
13
          font-size: 20px;
14
      }
15
      h1
16
      {
17
          text-align: center;
18
      }
19
      .hidden
20
      {
21
          display: none;
22
      }
23
24
      .buttons-wrapper
25
      {
26
          text-align: center;
27
      }
28
      .button-demo
29
      {
30
          padding: 0.5em;
31
          margin: 1em auto;
32
      }
33
      .author
34
      {
35
          display: block;
36
          margin-top: 1em;
37
      }
38
    </style>
39
   </head>
40
   <body>
41
    <h1>Vibration API</h1>
42
    <div class="buttons-wrapper">
43
      <button id="button-play-v-once" class="button-demo">Vibrate Once</button>
44
      <button id="button-play-v-thrice" class="button-demo">Vibrate Thrice</button>
45
      <button id="button-stop-v" class="button-demo">Stop</button>
46
    </div>
47
    <span id="v-unsupported" class="hidden">API not supported</span>
48
    <small class="author">
49
      Demo created by <a href="http://www.audero.it">Aurelio De Rosa</a>
50
      (<a href="https://twitter.com/AurelioDeRosa">@AurelioDeRosa</a>)
51
    </small>
52
    <script>
53
      window.navigator = window.navigator || {};
54
      if (navigator.vibrate === undefined) {
55
          document.getElementById('v-unsupported').classList.remove('hidden');
56
          ['button-play-v-once', 'button-play-v-thrice', 'button-stop-v'].forEach(function(elementId) {
57
            document.getElementById(elementId).setAttribute('disabled', 'disabled');
58
          });
59
      } else {
60
          document.getElementById('button-play-v-once').addEventListener('click', function() {
61
            navigator.vibrate(1000);
62
          });
63
          document.getElementById('button-play-v-thrice').addEventListener('click', function() {
64
            navigator.vibrate([1000, 500, 1000, 500, 2000]);
65
          });
66
          document.getElementById('button-stop-v').addEventListener('click', function() {
67
            navigator.vibrate(0);
68
          });
69
      }
70
    </script>
71
   </body>
72
</html>

Conclusion

In this article, we've learned about the Vibration API, what it is, how to use it, and when to use it. As we saw earlier, the API is very simple to use and provides us with an elegant way to improve the user experience on mobile devices, especially for things like movies and games. The Vibration API is supported fairly well on desktop and mobile browsers so nothing prevents you from using it today.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Web Design tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.