As the number of people using mobile is increasing day by day, the number of users accessing web on mobile is also increasing. This has led to the creation of several mobile web based games and apps. HTML5 is so powerful that today any kind of game or app can be created using it.
One cool feature of HTML5 is ‘Vibration API‘. Currently it is only supported in newer builds of firefox and chrome only. It can be used to improve user engagement in your mobile web app.
For example :
- You can use vibration in your mobile web game to show a hit with an enemy or when your car crashes etc.
- You can create a vibration when there is a new message in your chat app
- Or when there is a task going on in your app, and you can vibrate the phone when it is completed
Many users have their mobile phones in silent mode, so feature like vibration can provide great feedback.
Detecting if vibration is supported or not?
Vibration API is a part of Navigator API. So to check its availability, use the following code
if ("vibrate" in navigator) {
// vibration API supported
}
or, use this
// enable vibration support
navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;
if (navigator.vibrate) {
// vibration API supported
}
Creating Vibrations
Vibration API is very easy to use. All you need to do is call vibrate() function passing number of milliseconds or an array of milliseconds.
// vibrate for two seconds
navigator.vibrate(2000);
The above snippet creates a vibration for two seconds. You can simply pass the number of milliseconds you want the vibration to happen for.
// vibrate for one second
navigator.vibrate([200, 100, 400, 100, 200]);
The above snippet creates pattern of vibrations. The even number represents the time of vibration in milliseconds and odd represents the time delay between consecutive vibrations e.g. the above snippets creates a vibration for 200 ms and then wait for 100 ms, again vibrate for 400 ms and then wait for 100 ms and finally vibrate again for 200 ms.
Stopping a Vibration
Stopping a vibration is as easy as creating it. Simply call again vibrate() function with 0 as parameter or an empty array.
// Either of these stop vibration
navigator.vibrate(0);
navigator.vibrate([]);
Note: Vibration API is asynchronous, therefore creating a vibration will not affect the execution of JavaScript.
Go on to create your next amazing mobile web app or game and don’t forget to integrate it with our App42 Cloud APIs and AppWarp SDKs. If you have any questions or need any further assistance, please feel free to write us at support@shephertz.com
Leave A Reply