Web Standards, JavaScript, and Kittens

Menu

Example of adding menu support to a PhoneGap Application

Last night a fellow on Twitter asked about how to build in menu-key support in PhoneGap. I promised him a simple application that demonstrated this feature and would – hopefully – give him something to build on. Much like my earlier blog post on adding a context menu to a jQuery Mobile application, the process breaks down to two parts:
First – we build in support for noticing the menu button click. Second – we build the UI to create (or hide) a menu. Let’s take a look at a simple demonstration of this.

The official API docs for the menu button event demonstrates that it is rather trivial to listen for the click. Of course, this only applies to Android and Blackberry devices, but the code is just an event listener: document.addEventListener(“menubutton”, yourCallbackFunction, false);

I began with an HTML page that simply listened for this button and logged it to the console.

I pushed this to my device and confirmed that I could see when the menu button was clicked. (Need help with that? See this blog post on the topic.)

As I said – this part is trivial. Now that I know when the menu button is clicked, I need to create some type of UI element. Remember – I’m where design goes to die. Many Android apps tend to create a squarish menu towards the middle bottom of the application. So I created a div, positioned it, and hid it by default. I then used a tiny bit of JavaScript to either show or hide the div.

Nothing too much to it, right? Here’s how the application looks when I start it…

And here is it with the menu open:

That’s it. Obviously it could look a lot better. Also – my links don’t actually do anything. A real application would not only listen out for those clicks but also ensure they dispose of the menu. But hopefully this gives you enough to get started.

Share this:

Post navigation

Sponsors

The Author

I'm Raymond Camden, a developer advocate for IBM. My primary focus is on MobileFirst, hybrid mobile development, and client-side technologies. If you would like me to speak to your group, just drop me a line.