JS Vibration API Tutorial 🎯

beginner
11 min

JS Vibration API Tutorial 🎯

Welcome to our JS Vibration API tutorial! In this lesson, we'll dive into the world of creating vibrations on a user's device using JavaScript. This powerful feature is great for building interactive web applications, games, and notifications. Let's get started!

Introduction 📝

The Vibration API allows you to control the device's vibration motor, making it possible to add a tangible feedback layer to your web applications. This API is supported by modern mobile and desktop browsers.

Why use the Vibration API?

  • Adding a tactile feedback layer to your web applications
  • Enhancing user interaction and engagement
  • Building games, notifications, and more!

Getting Started 💡

To use the Vibration API, first ensure your browser supports it:

  • Chrome 34+
  • Firefox 39+
  • Safari 10+ (Desktop only)
  • Edge 15+

Now let's write some code!

Basic Vibration Example 🎯

javascript
// Request permission to access the vibration API navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; if (navigator.vibrate) { navigator.vibrate(200); // Vibrate for 200ms } else { console.log('Sorry, your browser does not support the Vibration API.'); }

In the above example, we're requesting permission to access the Vibration API and then vibrating the device for 200 milliseconds.

Advanced Vibration Patterns 💡

The Vibration API accepts an array of time durations and amplitudes. These patterns allow for more complex and creative vibration patterns in your applications.

Custom Vibration Pattern 🎯

javascript
navigator.vibrate([100, 500, 100, 500]); // Vibrate for 100ms, pause for 500ms, repeat twice

In this example, we're creating a custom vibration pattern consisting of 4 vibrations: 100ms, 500ms pause, 100ms, and another 500ms pause.

Stopping Vibration 💡

To stop a vibration, use the navigator.cancel method.

javascript
navigator.vibrate(200); // Start a vibration // After some time, stop the vibration setTimeout(function() { navigator.cancel; }, 1000);

Practical Applications 💡

  • Notifications: Use the Vibration API to create vibrating alerts
  • Games: Add a tactile feedback layer to your game for a more immersive experience
  • Accessibility: Provide a tactile aid for visually impaired users

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What is the Vibration API used for?

Quick Quiz
Question 1 of 1

What is the minimum duration of a vibration in milliseconds?