Last updated on November 7th, 2024 at 12:18 pm

When a web page is being loaded, the navigator.vibrate() function can be utilized to trigger vibrations on an iPhone or smartphone. This functionality can serve as a means to alert users, encouraging them to engage with specific features on your page or website.

For example, Here the device will vibrate for 1000 ms then pause for 500 ms then again start vibrating for 1000 ms.

if (navigator.vibrate) {
    navigator.vibrate([1000, 500, 1000]);
} else {
    console.log("Vibration not supported on this device.");
}

Let’s break it down step by step:

1. window.navigator:

  • window.navigator refers to the navigator object in the global window context, which provides information about the browser and the device. It is often used to access device capabilities, such as the device’s location, language, or in this case, the ability to vibrate.

2. vibrate() Method:

  • vibrate() is a method available in the Vibration API, which allows web applications to trigger vibration patterns on devices that support it (like smartphones or tablets). It can accept a number or an array of numbers as its argument.

3. The Argument [1000, 500, 1000]:

  • The argument [1000, 500, 1000] is an array that defines the vibration pattern, where each number represents a duration of vibration in milliseconds:
    • 1000: The device will vibrate for 1 second.
    • 500: The device will stop vibrating for 0.5 seconds.
    • 1000: The device will vibrate again for 1 second.

The numbers in the array represent alternating periods of vibration and pauses. In this case, the pattern is:

  • Vibrate again for 1 second.
  • Vibrate for 1 second.
  • Pause for 0.5 seconds.

You can also cancel the existing vibration by passing Navigator.vibrate() with a value of 0.

Save the below HTML file and run on your mobile / tab.

<body>
   <script type="text/javascript">
	  if (navigator.vibrate) {
     navigator.vibrate([1000, 500, 1000, 500, 1000, 500, 1000, 500, 1000, 500, 1000, 500, 1000, 500]);
} else {
    console.log("Vibration not supported on this device.");
}
   </script>
Just Vibrate, Run this page in a device which support vibration. For example Mobile phones (Smart Phones), Iphones, Tabs etc., It will not vibrate
</body>

When this code is executed, the device will vibrate in the specified pattern. This can be used in applications such as notifications, games, or any app where haptic feedback (vibration) is needed for user interaction or alerts.

Compatibility:

The Vibration API is supported on many mobile devices and some desktop browsers, but not all browsers support it, especially on desktops (e.g., Chrome and Firefox for mobile support it, but desktop versions do not). Therefore, before calling vibrate(), it’s a good practice to check if the device/browser supports it by verifying the existence of navigator.vibrate. This functionality is commonly used in mobile web applications to provide haptic feedback.

DEMO