Skip to content

Cordova - Vibration

The cordova-plugin-vibration allows your application to interface with the device’s vibration hardware. This can be used to provide haptic feedback for user actions or notifications.

Note: Vibration support and behavior can vary across platforms and devices. Some devices may not have vibration capabilities, or users might disable it.

To use the vibration API, you first need to add the plugin to your Cordova project. Open your terminal or command prompt and run:

cordova plugin add cordova-plugin-vibration

Let’s add a couple of buttons to index.html to trigger different vibration effects.

<!-- In index.html -->
<button id="simpleVibrateButton">Vibrate (3 Secs)</button>
<button id="patternVibrateButton">Vibrate Pattern</button>
<button id="cancelVibrateButton">Cancel Vibration</button>

In your index.js (or equivalent JavaScript file), set up event listeners for these buttons. Ensure this is done after the deviceready event.

// In index.js, after 'deviceready'
document.addEventListener('deviceready', () => {
document.getElementById("simpleVibrateButton").addEventListener("click", simpleVibrate);
document.getElementById("patternVibrateButton").addEventListener("click", patternVibrate);
document.getElementById("cancelVibrateButton").addEventListener("click", cancelVibration);
}, false);

The navigator.vibrate() method is used to control device vibration. It’s part of the HTML5 Vibration API, which this plugin exposes.

To vibrate the device for a specific duration (in milliseconds):

function simpleVibrate() {
// Vibrate for 3000 milliseconds (3 seconds)
if (navigator.vibrate) {
navigator.vibrate(3000);
console.log('Vibrating for 3 seconds...');
} else {
console.warn('Vibration API not supported on this device.');
alert('Vibration not supported.');
}
}

To vibrate with a pattern (an array of durations for alternating vibrations and pauses):

function patternVibrate() {
// Vibrate for 1 sec, pause for 1 sec, vibrate for 1 sec, pause for 1 sec, vibrate for 1 sec
// Pattern: [vibrate, pause, vibrate, pause, vibrate, ...]
const pattern = [1000, 1000, 1000, 1000, 1000];
if (navigator.vibrate) {
navigator.vibrate(pattern);
console.log('Vibrating with pattern:', pattern);
} else {
console.warn('Vibration API not supported on this device.');
alert('Vibration not supported.');
}
}

To cancel any ongoing vibration:

function cancelVibration() {
// Pass 0, an empty array, or an array with one 0 to cancel
if (navigator.vibrate) {
navigator.vibrate(0);
// Alternatively: navigator.vibrate([]);
console.log('Vibration cancelled.');
} else {
console.warn('Vibration API not supported on this device.');
}
}

Refer to the official cordova-plugin-vibration documentation and the MDN Web Docs for the Vibration API for more detailed information.