Making a vibrate alert (Mastering Sound and Music) (iPhone JavaScript)

In the previous recipe, you’ve learned how to create a simple notification using a beep sound. Continuing with notifications, we’re going to find out how to vibrate our device with JavaScript.

This recipe is very similar to the previous one. In fact, we’ll only need to change one line of JavaScript code for testing our new kind of notification.

You can find the complete code for this recipe at: code/ch0 5/vibrate/ in the code bundle.

Getting ready

As we’ve seen in the previous recipe, we’ll need the PhoneGap and UiUIKit frameworks plus the Xcode IDE. Remember that this IDE requires a Mac OS X operating system installed on your computer. Also, it’s important to keep in mind that you need to be a iPhone Developer Program member for installing and running your iPhone’s PhoneGap application in a real and physical device.

How to do it…

1. Let’s start reusing our code written for the previous recipe. Replace the make_beep () JavaScript function with the following new one:

tmp1A279_thumb


2. The next change will be to replace the name of the JavaScript function with the onclick handler of the anchor element. This element should refer to our new JavaScript function:

tmp1A280_thumb

3. In order to be consistent, we’ll change our header and the unordered list:

tmp1A281_thumb

4. Now we’re ready for testing. Save your new project and run it by clicking on the Build and Run button located at the top of the main Xcode window.

tmp1A282_thumb

5. Push the Click me! button for testing the device’s vibration effect.

How it works…

Triggering a vibration is pretty simple, thanks to the vibrate method of the notification object offered by PhoneGap. This method expects as parameter the number of milliseconds to vibrate the device. We used the value 4000 for four seconds.

As we’ve seen in the previous recipe, a simple button is used, which calls the code to trigger the vibration. An additional benefit of using UiUIKit, is that it helps us to build the user interface through a simple div element, an unordered list and an anchor HTML element.

See also

► Installing PhoneGap recipe in topic 1, Frameworks Make Life Easier

► Installing UiUIKit recipe in topic 1, Frameworks Make Life Easier

► Creating and customizing a notification box recipe in topic 2, Building Interfaces

► Making a beep alert recipe

Next post:

Previous post: