How to Make a Phone Vibrate Using JavaScript
Free Programmers

Free Programmers @free_programmers

About: Free Programmers

Joined:
Aug 20, 2024

How to Make a Phone Vibrate Using JavaScript

Publish Date: Aug 20 '24
106 51

In this tutorial, we’ll explore how to trigger the vibration function on a smartphone using JavaScript. This feature can be useful for creating more interactive and responsive web applications, particularly when targeting mobile users. Let’s dive into the details of how this can be implemented effectively.

  1. Introduction to the Vibration API

The Vibration API is a simple yet powerful feature available in modern web browsers that allows you to control the vibration functionality of a device. This API is primarily used on mobile devices, as most desktops do not have a vibration feature.

The API is straightforward and consists of a single method: navigator.vibrate(). When this method is called, it triggers the vibration of the device for a specified duration.

  1. Basic Usage of the Vibration API

The syntax of the vibrate() method is as follows:

navigator.vibrate(pattern);
Enter fullscreen mode Exit fullscreen mode

Here, pattern can be:

  • A single number representing the duration of vibration in milliseconds.
  • An array of numbers where odd indices represent vibration durations, and even indices represent pauses.

For example:

// Vibrate for 500 milliseconds
navigator.vibrate(500);

// Vibrate for 200ms, pause for 100ms, then vibrate for 200ms again
navigator.vibrate([200, 100, 200]);
Enter fullscreen mode Exit fullscreen mode

Practical Examples

  1. Simple Vibration on Button Click

Let’s start with a basic example where we trigger a vibration when the user clicks a button.

   <!DOCTYPE html>
   <html lang="en">
   <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Vibration API Example</title>
   </head>
   <body>
       <button onclick="navigator.vibrate(300)">Vibrate</button>
   </body>
   </html>
Enter fullscreen mode Exit fullscreen mode

In this example, clicking the button will cause the device to vibrate for 300 milliseconds.

  1. Patterned Vibration

You can create more complex vibration patterns by using an array of numbers. Each odd index in the array defines a vibration duration, and each even index defines a pause.

   <button onclick="navigator.vibrate([100, 50, 100, 50, 300])">Vibrate Pattern</button>
Enter fullscreen mode Exit fullscreen mode

In this example, the phone will vibrate in the following pattern: 100ms vibration, 50ms pause, 100ms vibration, 50ms pause, 300ms vibration.

Stopping Vibration

To stop a vibration that is currently in progress, you can call the vibrate() method with a value of 0 or an empty array:

navigator.vibrate(0);
// Or
navigator.vibrate([]);
Enter fullscreen mode Exit fullscreen mode

Checking Browser Support

Not all browsers or devices support the Vibration API. Before using the vibration feature, it’s a good practice to check if the API is supported:

if ("vibrate" in navigator) {
   console.log("Vibration API is supported");
} else {
   console.log("Vibration API is not supported");
}
Enter fullscreen mode Exit fullscreen mode

Real-World Use Cases

  • Notifications: Trigger a short vibration when receiving a notification on a web app.
  • Games: Enhance user experience by adding vibration feedback when interacting with game elements.
  • Alerts: Alert users to critical updates or warnings by using a distinctive vibration pattern.

Considerations and Best Practices

  • Battery Consumption: Frequent or prolonged vibrations can drain the device's battery quickly. Use vibrations sparingly.
  • User Experience: Excessive vibrations can be annoying or distracting. Always provide users with the option to disable this feature.
  • Accessibility: Keep in mind that some users may rely on vibrations as part of their accessibility settings. Ensure that your application respects these settings.

Conclusion

The Vibration API in JavaScript is a simple yet effective way to enhance the interactivity of your web applications, especially for mobile users. Whether you're creating a game, building notifications, or just adding a bit of flair to your UI, the ability to trigger vibrations can significantly improve user engagement. Remember to use this feature judiciously to ensure a positive user experience.
Telegram channel:
https://t.me/Free_Programmers

Comments 51 total

  • Himanshu Sorathiya
    Himanshu Sorathiya Aug 20, 2024

    Wow, great article, thanks for this

  • Techninjax
    TechninjaxAug 20, 2024

    Thanks for the updates

  • Django
    DjangoAug 21, 2024

    Nice, still wish this still had better support



    Data on support for the vibration feature across the major browsers from caniuse.com

  • Sanjay Paul
    Sanjay PaulAug 21, 2024

    Great tutorial! The Vibration API is a neat tool for adding a touch of interactivity to your mobile web apps. Whether you're enhancing user feedback in a game or making notifications pop, this guide covers all the essentials. Just remember to use vibrations wisely to keep your users happy and engaged!

    • JoelBonetR 🥇
      JoelBonetR 🥇Aug 21, 2024

      Totally agree! The Vibration API can really elevate the user experience when used correctly. Do you have any examples of where you've implemented it in your projects? I'm curious to see how others are creatively using it.

      PS: Commenting using AI it's the dumbest thing ever

    • Free Programmers
      Free ProgrammersAug 21, 2024

      👍

    • Free Programmers
      Free ProgrammersAug 21, 2024

      💯

  • CodePassion
    CodePassionAug 21, 2024

    This is a cool feature that I can definitely see adding some extra interactivity to web apps.

  • Amir Majd
    Amir MajdAug 21, 2024

    It was really awesome💯

  • roshan khan
    roshan khanAug 21, 2024

    web games created can use this feature. great write on the vibration API.

  • Martin Baun
    Martin BaunAug 21, 2024

    Pretty neat! It’s nice for feedback on web apps that have a unique UX. For example, you might have something that does an action on press and on long press, so if a user presses down and wait 1000ms, you can perform the long press action and vibrate to let the user know they can let go now.

    I however don’t think vibration has a place in 99.9% of sites though

  • Debajyati Dey
    Debajyati DeyAug 21, 2024

    great articles! Thanks for sharing the knowledge!

  • Anna Villarreal
    Anna VillarrealAug 21, 2024

    Love it! Thanks for sharing.

  • Syed Muhammad Ali Raza
    Syed Muhammad Ali RazaAug 22, 2024

    👍

  • ProgKids
    ProgKidsAug 22, 2024

    Great!

  • AlgoT
    AlgoTAug 22, 2024

    Watch this get abused...

  • Abdul Arham
    Abdul ArhamAug 22, 2024

    👍

  • Dan Silcox
    Dan SilcoxAug 22, 2024

    Nice, can't wait for all those 'sign up to our newsletter' popups to vibrate at me :D

  • Hadeh
    HadehAug 23, 2024

    great feature

  • Hanzla Baig
    Hanzla BaigAug 23, 2024

    👍👍👍👍

  • Raziel Rodrigues
    Raziel RodriguesAug 23, 2024

    I will create an app with this ͡° ͜ʖ ͡°)

  • Junaid
    JunaidAug 23, 2024

    Vaddas doesn't appear to be a widely recognized term with a specific meaning in general usage. It could be a name, brand, or term specific to a certain context or region. If you have more context or if it's related to a specific industry, topic, or language, I can provide a more accurate description.

  • mohamed karim
    mohamed karimAug 23, 2024

    Thank for sharing

  • Elis Kaholwe
    Elis KaholweAug 24, 2024

    And here we go !

  • Free Programmers
    Free ProgrammersAug 24, 2024

    The big codes were the ones that worked!!

  • Iain Simmons
    Iain SimmonsAug 24, 2024

    Good post, and I learnt something new today!

    One thing though, you mentioned odd and even indices a couple of times, but JavaScript has zero-based indexing, so the first integer in the array is the zeroth index and technically even, the second integer is index 1 and an odd index.

    But I get how it could be difficult to communicate it without confusing people. Maybe talking about the odd and even positions in the array?

  • Andrea Gelmini
    Andrea GelminiAug 29, 2024

    Image description

    Chrome on my PC confirms api support. Too bad it can't vibrate I would have liked to make it dance a bit.

    • Free Programmers
      Free ProgrammersAug 29, 2024

      logically!!!

      • Andrea Gelmini
        Andrea GelminiAug 30, 2024

        To be honest, I was expecting him to tell me that I wasn't available.
        Although, the idea of making the desk dance had gassed me. :-D

  • Joaquin Cavenaghi
    Joaquin CavenaghiSep 17, 2024

    Great article!
    I'm thinking of using vibrate app for my university final paper, I need to know if it's possible to manage the intensity of the vibration as well as the time. I understand that in the current version it is not, but maybe someone knows an alternative?
    greetings from argentina.

Add comment