O'Reilly

Vibration API

By on  

Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in a pattern for a given duration.

Detecting Vibration API Support

It's always good to check for the presence of API support before using it;  here's how you can detect the Vibration API's presence:

// Standards ftw!
var supportsVibrate = "vibrate" in navigator;

The Vibration API consists of only one method provided to the window.navigator object:  vibrate.

Vibration API Basics

The navigator.vibrate function accepts either a single number or an array of numbers for a series of vibrations. When using the array method, the even indices represent vibration duration, the odd indices represent a delay before the next vibration.

// Vibrate once for one second
navigator.vibrate(1000);

// Vibrate multiple times for multiple durations
// Vibrate for three seconds, wait two seconds, then vibrate for one second
navigator.vibrate([3000, 2000, 1000]);

To stop vibration when active, simply pass a 0 or an empty array to the navigator.vibrate method:

// Either of these stop vibration
navigator.vibrate(0);
navigator.vibrate([]);

Realize that vibrations do not loop until stopped with 0 or an empty array;  the single number vibration occurs once and then becomes silent, the array of vibration durations run and becomes silent again.

Continued Vibration

Some basic setInterval and clearInterval action will allow us you to create persistent vibration:

var vibrateInterval;

// Starts vibration at passed in level
function startVibrate(duration) {
	navigator.vibrate(duration);
}

// Stops vibration
function stopVibrate() {
	// Clear interval and stop persistent vibrating 
	if(vibrateInterval) clearInterval(vibrateInterval);
	navigator.vibrate(0);
}

// Start persistent vibration at given duration and interval
// Assumes a number value is given
function startPeristentVibrate(duration, interval) {
	vibrateInterval = setInterval(function() {
		startVibrate(duration);
	}, interval);
}

Of course the snippet above doesn't take into account the array method of vibration;  persistent array-based vibration will require calculating the sum of the array items and creating an interval based on that number (with an additional delay, probably).

Why Use the Vibration API?

This API is clearly targeted toward mobile devices.  The Vibration API would be good for alerts within mobile web applications, and would be especially awesome when used in games or media-heavy applications.  Imagine watching a video on your mobile device, and during an explosion scene, your phone got a bit of a shake.  Or playing Bomberman and feeling a gentle kick when a block explodes!

What do you think of the Vibration API:  immediately useful or not quite yet?

At the time of writing, Firefox BETA for Android is the only browser which supports the Vibration API. WebKit landed the Vibration API a while back, but in my testing of iOS Chrome and Safari, as well as Android Chrome and standard browser, I could not find a working vibration property. Opera doesn't appear to support vibration yet either.

Track.js Error Reporting

Recent Features

  • Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() – this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

  • Responsive Images: The Ultimate Guide

    Chances are that any Web designers using our Ghostlab browser testing app, which allows seamless testing across all devices simultaneously, will have worked with responsive design in some shape or form. And as today’s websites and devices become ever more varied, a plethora of responsive images...

Incredible Demos

  • JavaScript Canvas Image Conversion

    At last week's Mozilla WebDev Offsite, we all spent half of the last day hacking on our future Mozilla Marketplace app. One mobile app that recently got a lot of attention was Instagram, which sold to Facebook for the bat shit crazy price of one...

  • Create a Simple Slideshow Using MooTools

    One excellent way to add dynamism to any website is to implement a slideshow featuring images or sliding content. Of course there are numerous slideshow plugins available but many of them can be overkill if you want to do simple slideshow without controls or events....

Discussion

  1. Great article, appreciate the code samples. I think this could be great if it’s widely supported and used properly. I’d like to see mobile browsers add an option to turn it off, like you can with location services. It could be very annoying if a website is constantly buzzing at me.

  2. @Steve Edson I don’t believe it should need to ask. If it’s annoying just close the site. I tested it and it won’t run in the background if Firefox isn’t the focused application.

    I know where you’re coming from w/ it being annoying, but it’s the same w/ popups, popunders, blink, css3 animations, etc… if you don’t like it, close it and blame the developer for using it improperly. :)

    • Good point Andrew. Features that are more invasive, like Geolocation and getUserMedia, do require permission via prompt; vibration isn’t invasive but could be misused. That said, browsers do provide popup blocking so…who knows. I wouldn’t be opposed to the Vibration API being a setting.

  3. Hey Dave,

    Nice write-up!

    Speaking of standards, shouldn’t the sniff for “vibrate” look more like the following?

    // Standards ftw!
    var supportsVibrate = "vibrate" in (clientInformation || navigator);
    

    Regards,

    — John

  4. Chris Strat

    That is brilliant – I am loving how there are API expanding deeper into the device.

    One that I am really keen on finding is one to prevent the screen from dimming/locking.
    Are you aware of any that are out there that work across iPhone and Android browsers?

  5. Rick

    Next thing I want to see is desktop browsers providing support for these things.

    Vibrate, for example, could make the tab jiggle. Or play a fake vibrate noise.

  6. “Make the tab jiggle” !? Please God no ! A persistent animation was annoying enough, imagine shaking all the content of a tab.
    I think it can be well used on a mobile : i once developed a site where alert windows could be critical (a one-cent bidding playful website), and buzzing could have been a real plus on mobiles.

  7. Alex

    Maybe pr0n companies will adopt this “new technology” faster than the rest of us… AGAIN :P

  8. psobko

    I really hope this never comes to my iPhone. Apple’s had a history of cracking down on apps that abuse vibration, in fact it’s even impossible to create a sustained vibration with the iOS SDK. The last thing we need is unregulated access to this feature. The less hardware the browser has access to, the better.

  9. Ravindran

    I hope user should get some say/allow on whether he should allow the site to use vibrate API. (similar to desktop notification API in Chrome desktop browser)

    In desktop era, SetForegroundWindow (http://msdn.microsoft.com/en-us/library/windows/desktop/ms633539(v=vs.85).aspx) is the most abused API by desktop applications. Eventually Microsoft changed the behavior to just flash the taskbar entry.

  10. I really love the MSN nudge idea: http://dev.ih8.nl/demos/vibrate/ No, really! We need more bling

  11. Bart Nelis

    Thanks for this article, this could prove very useful indeed !

  12. Bart Nelis

    Very interesting feature, thx for the article. This could prove very useful .

  13. The Vibration API is still primarily unsupported.

  14. You should put “WARNING: ONLY WORKS FOR FIREFOX BROWSER” at the top of this page.

  15. alexandervrs

    Is this designed to work along with the Gamepad API to enable vibration support for gamepads or is this mobile device only?

  16. Loupax

    I found it really that my browser on the desktop supports vibrate, but disappointed that it didn’t actually do anything.

    It would be nice to apply a pseudo class at the body element, so the developers can provide visual feedback in case that vibrate doesn’t work

  17. TheCuBeMan

    What mobile web browsers types and version support the vibrate API?

  18. TheCuBeMan

    What mobile web browsers support this Vibrate API?

  19. Ravindran

    >>What mobile web browsers support this Vibrate API?
    You can check here.
    http://caniuse.com/#search=vibration

  20. Andrei

    Well, the vibration API does not work on Chrome with Android Lollipop 5.1, although I get ("vibrate" in navigator) == true.

    Firefox works! but does not accept the vibration patterns.

    • Boris

      >> Firefox works! but does not accept the vibration patterns.
      Hey, Andrei!
      I’ve published a library that reduces that inconsistence:
      http://borischumichev.github.io/vibr8/

    • Andrei

      Hey Boris, nice job!
      Looks awesome!

      Had any luck using the API on other devices/operating systems?

  21. bingb511

    The Vibration API is still primarily unsupported.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • OSCON Portland:  Conference  Discount!

    O'Reilly puts on the best web industry conferences in the world.  These conferences include Fluent Conference, Velocity Conference, and the upcoming OSCON in Portland, Oregon from July 20-24.  Open Source Convention (OSCON) is a conference that focuses specifically on open source developers and the tools and possibilities...

  • Follow Redirects with cURL

    I love playing around with cURL. There's something about loading websites via command line that makes me feel like some type of smug hacker, just like tweeting from command line does. I recently cURL'd the Google homepage and saw the following: I found it weird that Google...

  • Developers Have WordPress, Amateurs Have Squarespace, Professional Designers Have the NEW Webydo!

    Web design platforms have traditionally come in one of two varieties. There are the solutions like WordPress and Drupal that are incredibly powerful, but an understanding of web development and coding is required to be able to use those platforms effectively. On the other side of the...

  • Chris Coyierâs Favorite CodePen Demos II

    Hey everyone! Before we get started, I just want to say it’s damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so...

  • GSAP + SVG For Power Users: Motion Along A Path

    Now that the GreenSock API is picking up steam, there are many tutorials and Getting Started guides out there to provide good introductions to the library, not to mention GreenSock’s own Forum and Documentation. This article isn’t intended for beginners, but rather a...