Advertisement

HTML5: Vibration API

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →

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.

if (window.navigator && window.navigator.vibrate) {
   // Shake that device!
} else {
   // Not supported
}

Another option is to inspect the navigator object.

if ('vibrate' in navigator) {
   // Shake that device!
} else {
   // Not supported
}

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:

// Vibrate once for 1 second
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:

// Vibrate three times
// First two vibrations last one second
// Last vibration lasts two seconds
// Pauses are half a second
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.

// Stop vibrating
navigator.vibrate(0);

Or:

// Stop vibrating
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.

<!DOCTYPE html>
<html>
   <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta name="author" content="Aurelio De Rosa">
    <title>Vibration API Demo by Aurelio De Rosa</title>
    <style>
      body
      {
          max-width: 500px;
          margin: 2em auto;
          font-size: 20px;
      }
      h1
      {
          text-align: center;
      }
      .hidden
      {
          display: none;
      }

      .buttons-wrapper
      {
          text-align: center;
      }
      .button-demo
      {
          padding: 0.5em;
          margin: 1em auto;
      }
      .author
      {
          display: block;
          margin-top: 1em;
      }
    </style>
   </head>
   <body>
    <h1>Vibration API</h1>
    <div class="buttons-wrapper">
      <button id="button-play-v-once" class="button-demo">Vibrate Once</button>
      <button id="button-play-v-thrice" class="button-demo">Vibrate Thrice</button>
      <button id="button-stop-v" class="button-demo">Stop</button>
    </div>
    <span id="v-unsupported" class="hidden">API not supported</span>
    <small class="author">
      Demo created by <a href="http://www.audero.it">Aurelio De Rosa</a>
      (<a href="https://twitter.com/AurelioDeRosa">@AurelioDeRosa</a>)
    </small>
    <script>
      window.navigator = window.navigator || {};
      if (navigator.vibrate === undefined) {
          document.getElementById('v-unsupported').classList.remove('hidden');
          ['button-play-v-once', 'button-play-v-thrice', 'button-stop-v'].forEach(function(elementId) {
            document.getElementById(elementId).setAttribute('disabled', 'disabled');
          });
      } else {
          document.getElementById('button-play-v-once').addEventListener('click', function() {
            navigator.vibrate(1000);
          });
          document.getElementById('button-play-v-thrice').addEventListener('click', function() {
            navigator.vibrate([1000, 500, 1000, 500, 2000]);
          });
          document.getElementById('button-stop-v').addEventListener('click', function() {
            navigator.vibrate(0);
          });
      }
    </script>
   </body>
</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