Most modern mobile devices include vibration hardware, Adding vibration to your website or PWA gives the user haptic feedback by causing the device to shake. If you are making video games and/or mobile apps using vibration can alleviate the experience. Continue reading to know more about how to add vibration to your website or PWA.
While adding vibration to your web app, it is essential that vibration should be used as an addon and not for communicating functionality. Most browser provide functionality to vibrate the device if underlying device supports the same. if it doesn’t the call will simply return and will not break your code.
A single vibration
You can pulse the vibration hardware by providing a single value or single value in an array
window.navigator.vibrate(500);
window.navigator.vibrate([500]);
Vibration pattern
An array of values describes alternating periods in which the device is vibrating and not vibrating. It generally converts to milliseconds.
window.navigator.vibrate([73, 82, 100, 171, 195]);
Cancelling Vibration
Calling method with a value of 0
, an empty array, or an array containing all zeros will cancel any currently ongoing vibration pattern.
window.navigator.vibrate([]);
window.navigator.vibrate(0);
Know before adding vibration to a website
Since JavaScript is used on both servers and clients in different environments. Currently, there is no way to determine if the hardware supports vibration or not with a hundred percent accuracy. Although we can use some workaround to detect whether it’s a mobile device or not using resolution and user-agent, in case you want to provide a toggle to on/off the vibration effect which I think you should as it can be annoying sometimes.
JavaScript Snippet for vibration utility
I learned about these while developing a PWA Game Moody Man