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!
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.
To use the Vibration API, first ensure your browser supports it:
Now let's write some code!
// 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.
The Vibration API accepts an array of time durations and amplitudes. These patterns allow for more complex and creative vibration patterns in your applications.
navigator.vibrate([100, 500, 100, 500]); // Vibrate for 100ms, pause for 500ms, repeat twiceIn this example, we're creating a custom vibration pattern consisting of 4 vibrations: 100ms, 500ms pause, 100ms, and another 500ms pause.
To stop a vibration, use the navigator.cancel method.
navigator.vibrate(200); // Start a vibration
// After some time, stop the vibration
setTimeout(function() {
navigator.cancel;
}, 1000);What is the Vibration API used for?
What is the minimum duration of a vibration in milliseconds?