As part of Mozillas WebAPI effort, we have been working with bringing a Vibration API to all devices that support it.
The idea with the Vibration API is to be able to give the user a notification, in a game or other use case, by telling the device to vibrate. It accesses the native vibrator and tells it how long it should vibrate.
Examples
The way to do this is quite simple – in this example the parameter is how long it should vibrate, i.e. the number of milliseconds:
navigator.mozVibrate(1000);
Another way of controlling vibration is giving a vibration pattern, switching between vibrating and being still. The odd parameters in the list is vibration time, the even ones are pauses:
navigator.mozVibrate([200, 100, 200, 100]);
And if you want to stop the vibration, you can simply call the mozVibrate
method with an argument of 0 or an empty pattern, like this:
navigator.mozVibrate(0);
navigator.mozVibrate([]);
Try it out!
If you want to try this out right now, you can do so in Firefox Aurora, which is planned to become Firefox 11. Currently, it naturally only works on devices that support vibration, which means Firefox on (most) Android phones.
Note: a possbile caveat could be if you have haptic feedback turned on on your Android device, which then might cancel out the vibration.
Demo
I put together a little demo where you can see the code needed and test it in place. Please play around with this and let us know what you think!
Edit: Our temporary implementation name was Vibrator API, but since it gave the wrong impression, we now call it Vibration API – which is also more in line with the W3C Vibration API draft.
About Robert Nyman [Editor emeritus]
Technical Evangelist & Editor of Mozilla Hacks. Gives talks & blogs about HTML5, JavaScript & the Open Web. Robert is a strong believer in HTML5 and the Open Web and has been working since 1999 with Front End development for the web - in Sweden and in New York City. He regularly also blogs at http://robertnyman.com and loves to travel and meet people.
34 comments