Menu

How to Use the Vibration API for Haptic Feedback in Mobile Web Applications

How to Use the Vibration API for Haptic Feedback in Mobile Web Applications

The JavaScript Vibration API is a powerful yet simple tool that allows developers to trigger vibrations on mobile devices directly through their web applications. This API opens up opportunities for more immersive, responsive mobile experiences without requiring native app development.

In this article, I'll walk through how to use the Vibration API for adding haptic feedback to your mobile web applications, explore common use cases, and provide working code examples.

What is the Vibration API?

The Vibration API is a web API that allows developers to programmatically control the vibration hardware in mobile devices through JavaScript. And yes, that means that the device in question must support vibration, as well as the browser. More on that below.

The API can trigger vibrations in different patterns that the developer can specify, giving users tactile feedback for specific actions.

While the Vibration API is not supported on all devices or browsers, it is widely available on modern mobile browsers like Chrome and Firefox. Its simplicity makes it an ideal choice for adding subtle feedback to actions such as form submissions, button presses, or even as part of a mobile game.

Here’s a quick list of browsers that support the Vibration API:

It’s important to note that this API is not supported in desktop browsers (except some rare cases with specific hardware), so its use case is largely limited to mobile web apps.

Basic Usage of the Vibration API

Using the Vibration API is as simple as calling a function within your JavaScript code. The API offers two basic methods of triggering vibrations: a single vibration and a patterned vibration. I'll show an example of both below.

Single Vibration Example

A single vibration can be triggered with a single value representing the duration (in milliseconds) of the vibration:

// Trigger a single vibration lasting 200 milliseconds
navigator.vibrate(200);

In this example, the device will vibrate for 200 milliseconds (or 0.2 seconds).

Patterned Vibrations Example

You can also create a series of vibrations and pauses by passing an array of numbers. Each number in the array alternates between the vibration duration and pause duration.

// Trigger a pattern of vibrations: 200ms on, 100ms off, 200ms on
navigator.vibrate([200, 100, 200]);

In this case, the device will vibrate for 200 milliseconds, pause for 100 milliseconds, and then vibrate again for 200 milliseconds.

You can essentially create a different pattern for various different use cases so that users can get familiar with each the more they interact with your mobile application.

Stopping a Vibration

If you need to stop an ongoing vibration pattern, you can pass 0 to the vibrate() method:

// Stop any ongoing vibration
navigator.vibrate(0);

Practical Use Cases for the Vibration API

The Vibration API can be used in a wide variety of applications. Below are some practical examples of how you can integrate haptic feedback into your mobile web projects:

1. Button Press Feedback

When a user clicks a button, you can add a short vibration to provide tactile feedback, signaling that the button press was successful.

document.querySelector('#myButton').addEventListener('click', function() {
    navigator.vibrate(100);  // 100ms vibration for button press feedback
});

2. Form Submission Confirmation

You can trigger a vibration when a form is successfully submitted, providing an additional confirmation to the user.

document.querySelector('#myForm').addEventListener('submit', function(e) {
    e.preventDefault();
    navigator.vibrate(200);  // 200ms vibration for form submission
});

3. Error Alerts

Vibrations can be used to alert users when an error occurs, especially useful in mobile apps where visual alerts can sometimes go unnoticed.

function showError() {
    navigator.vibrate([300, 100, 300]);  // Patterned vibration to signal error
    alert('Error occurred!');
}

4. Mobile Game Interactions

In mobile games, vibrations can be used to make in-game actions more immersive. For instance, you can trigger a vibration when a player hits an obstacle or wins a level.

function winLevel() {
    navigator.vibrate(100);  // Short vibration to celebrate level completion
}

Why Use Haptic Feedback?

Haptic feedback, commonly in the form of device vibrations, can greatly enhance the user experience in mobile applications. It adds a new layer of interactivity, making the app feel more responsive and engaging.

But it's also important to not overdo it, as that can negatively impact the user experience as well. If a phone vibrates during an action where it doesn't make sense, that can leave users confused assuming that something just happened, but they can't figure out what.

Browser Compatibility and Fallbacks

While the Vibration API is fairly well-supported across major mobile browsers, it’s important to ensure your web app degrades gracefully on browsers that do not support it.

You can easily check if the Vibration API is supported using the following code:

if ("vibrate" in navigator) {
    // API is supported, you can use navigator.vibrate here
    navigator.vibrate(200);
} else {
    // Vibration API not supported, handle gracefully
    console.log("Vibration API not supported on this device.");
}

This ensures that your web application remains functional on devices where vibration is not available.

Best Practices for Implementing Haptic Feedback

Keep the following best practices in mind:

Use sparingly: Only add haptic feedback where it provides real value. Too many vibrations can make your app feel disruptive.

Provide an option to disable: Always offer users a way to disable haptic feedback in the settings or preferences.

Test across devices: Vibration strength and duration can vary significantly between different mobile devices. Test on multiple devices to ensure a consistent experience.

Avoid in long durations: Prolonged vibrations can drain battery life, especially if used excessively in an app.

Conclusion

The Vibration API is a simple yet effective tool for enhancing mobile web applications through haptic feedback. Whether you’re adding subtle vibrations to buttons or creating complex feedback for a mobile game, the API offers an easy way to integrate tactile responses into your app.

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

No comments posted yet

Add a comment