HTML5 Vibration API: Vibrator test, Examples, Plugins, and Code

10 min read
Vibration API Icon

Have you ever wanted to make your phone vibrate right from a website using JavaScript?

In this complete guide, you'll learn how to leverage the new HTML Vibration API to create immersive web experiences by adding vibration effects with just a few lines of JavaScript code.

Why Use the Vibration API on Websites?

Vibration effects can provide tactile feedback to enhance UX for mobile users. When used sparingly, vibrations can make web elements feel more interactive without being annoying or overused.

Some great uses cases:

  • Provide haptic feedback on button clicks
  • Notifications and alerts
  • Fun effects paired with music or themes

With careful design, vibrations can significantly improve the UX on mobile sites and apps. ✨

Let's take a quick look at how it works:

// Vibrate for 1 second
navigator.vibrate(1000); 

In this complete guide you'll learn:

So if you want to make your web projects vibrate, buzz, shake, and rattle - let's get started!

Vibration API Browser Support

The Vibration API is supported in most modern browsers, but there are some exceptions:

Device/BrowserSupport
iOS Safari❌ No
Opera Mini❌ No
IE❌ No
Android Browser✅ Since Android 4.4
Chrome✅ Yes!
Firefox✅ Yes!
Your Browser

The vibration API is implemented in navigator.vibrate. So calling the function makes your phone vibrate. You can test if your browser is recent enough to have the vibrate function in navigator. To check for support in JavaScript:

if ("vibrate" in navigator) {
  // vibration supported!
}

There are some key limitations:

  • Requires actual vibration hardware in the device
  • Page needs to be visible - doesn't work in background tabs
  • Some browsers limit excessive vibration

Now let's look at how to actually trigger vibrations!

Usage of navigator.vibrate

The navigator.vibrate function either accepts a number or an array of numbers.

In the following example the device will vibrate for 1000 milliseconds (ms):

Test Code

// vibrate for 1000 ms
navigator.vibrate(1000)
 
// or alternatively
navigator.vibrate([1000])

The vibration pattern is formed by milliseconds of duration of the vibration and the duration of the waiting period.

In this example the devices will vibrate for 1000 ms, wait 500 ms and vibrate again.

Test Code

// device will     vibrate    wait    vibrate
navigator.vibrate([1000, 500, 1000])

Any new call stops the previous vibration sequence. If the page is no longer visible, like locking the device, minimizing the window, moving to another tab then the vibration also stops.

In this example the devices will stop vibrating.

Test Code

// Stop vibrating
navigator.vibrate()
navigator.vibrate(0)
navigator.vibrate([])

How to Vibrate your Phone on the Web

We can keep vibrating until the user stops touching the device. The vibration stops after a while though. But it's not meant to be pressed infinitely anyway.

In this example the device will keep vibrating until the touch event has stopped

Test Code

var isMobile = /iPhone|iPod|iPad|Android|BlackBerry/.test(navigator.userAgent)
 
$('.button').on(isMobile ? 'touchstart' : 'mousedown', function (e) {
  navigator.vibrate(Infinity) // Infinity is a number
})
 
$('.button').on(isMobile ? 'touchend' : 'mouseup', function (e) {
  navigator.vibrate(0)
})

Vibrate on click

The best use case I can imagine for this API is for buttons. You get a little haptic feedback like you get for native apps. This can be done by setting the vibration to a very low number. For me 50ms seems ideal.

In this example all buttons and links on this page vibrate on tap. We also detect if the device is mobile and use touchend.

Test Code

var isMobile = /iPhone|iPod|iPad|Android|BlackBerry/.test(navigator.userAgent)
 
$('.button, a').on(isMobile ? 'touchend' : 'click', function (e) {
  navigator.vibrate(50)
})

Vibrate via checkboxes

Vibrating after clicking a sliding checkbox is also very helpful. It feels really natural. There is a short vibration at the start, then a period of waiting whilst the checkbox is moving and then a longer vibration at the end.

In this example, the checkbox will vibrate.

<div className="ui slider checkbox">
  <input id="product-1" type="checkbox" />
  <label htmlFor="product-1">Duvel</label>
</div>
<div className="ui slider checkbox">
  <input id="product-2" type="checkbox" />
  <label htmlFor="product-2">Jupiler</label>
</div>
$('.ui.checkbox').click(function () {
  navigator.vibrate([5, 200, 20])
})

Vibration Duration

If you're not sure how long the haptic feedback should be. You can experiment with various timespans. Try all of these buttons out a mobile device. Anything above 100ms seems to long for me.

In this example the following buttons vibrate each on a different timespan.

Vibrate on notification

Another great use case are for notifications. These can be a bit longer than haptic feedback. Patterns can also be used to differentiate.

Please be aware of the vibration notification on the phone and try not to replicate them as to not to confuse the user. Some visual feedback together with the vibration would be ideal.

Click the buttons below. When the progress bar reaches the end. You get a notification! Each button is a different vibration pattern.

// Vibrate on completion
var pattern = [500, 100, 500];
$(".progress .bar")
    .css({width: "0%"})
    .animate({width: "100%"}, {
        duration: 1000,
        complete: function() {
            if (canVibrate) navigator.vibrate(pattern);
        }
    });

Vibration with Song Patterns

Groggie mentioned his blog post on using the Vibration API for music and theme songs. It's a really cool example of what can be done using the Vibration API and some creative thought. Click on the titles below to play.

navigator.vibrate([
  125, 75, 125, 275, 200, 275, 125, 75, 125, 275, 200, 600, 200, 600,
])
navigator.vibrate([
  200, 100, 200, 275, 425, 100, 200, 100, 200, 275, 425, 100, 75, 25, 75, 125,
  75, 25, 75, 125, 100, 100,
])
navigator.vibrate([
  500, 110, 500, 110, 450, 110, 200, 110, 170, 40, 450, 110, 200, 110, 170, 40,
  500,
])
navigator.vibrate([
  100, 30, 100, 30, 100, 200, 200, 30, 200, 30, 200, 200, 100, 30, 100, 30, 100,
])

Vibration API Code Examples

Vue.js Vibration

I used to write my own Vibration API code in Vue.js, but with the hooks being introduced into Vue 3, I started using a hook called useVibrate from @vueuse/core.

import { useVibrate } from '@vueuse/core'
 
// Vibrate the device for 300 ms, wait 100 ms, vibrate for 300 ms
const pattern = [300, 100, 300]
const { vibrate, stop, isSupported } = useVibrate({ pattern })
 
vibrate() // will stop after the pattern is finished
 
stop() // stop vibration immediately

Next.js and React vibration

In Next.js and React, you can use the Web Vibration API directly in functional components. Here's an example of how you can create a custom hook to handle vibrations:

"use client"
import { useCallback } from 'react';
 
export function useVibration(pattern) {
  const vibrate = useCallback(() => {
    if ('vibrate' in navigator) {
      navigator.vibrate(pattern);
    }
  }, [pattern]);
 
  return vibrate;
}

You can then use this hook in your components to trigger vibrations based on user interactions or other events.

Otherwise, here's an example of how you can create a button that vibrates when clicked:

'use client'
 
// Only possible in the browser and Client components
function VibrateButton({ pattern }) {
  const handleClick = () => {
    if ('vibrate' in navigator) {
      navigator.vibrate(pattern);
    }
  };
 
  return (
    <button onClick={handleClick}>
      Click to Vibrate
    </button>
  );
}
 
// Use the VibrateButton component in your app
<VibrateButton pattern={[300, 100, 300]} />

jQuery.vibrate.js

If doing it manually seems difficult for you, I've written a jquery plugin that can get you started right away.

Download and embed the code then initialize in one of the following ways:

// Vibration for 50ms on all .button on click
$('.button').vibrate()
 
// Vibrate for 20ms on click
$('.button').vibrate('short')
 
// Vibrate for 50ms on click
$('.button').vibrate('medium')
$('.button').vibrate('default')
$('.button').vibrate(50)
 
// Vibrate for 100ms on click
$('.button').vibrate('long')
 
// Vibrate for 1000ms on touchstart. Stop vibrating on touchend.
$('.button').vibrate({
  duration: 1000,
  trigger: 'touchstart',
})

I also made a slideshow: Learn About The Vibration API from Illyism. Feel free to share it and show it around.

Interested in more Javascript and CSS articles? Check out our article on CSS Text Gradients.

Ilias is a SEO entrepreneur and marketing agency owner at MagicSpace SEO, helping small businesses grow with SEO. With a decade of experience as a CTO and marketer, he offers SEO consulting and SEO services to clients worldwide.

Exclusive offers

The best deals for makers and creators.

SEO Agency
Need help with SEO? Get a free consultation from MagicSpace SEO.
Get Consultation
MagicBuddy
Get 10 free credits for MagicBuddy, the AI chatbot for Telegram.
Chat Now
OG Image Generator
Just copy & paste the source code & never worry about OG images again.
Get Lifetime deal
Gradient Wallpapers
Discover GradientPage, your source for gradient wallpapers.
Get Wallpapers