Saturday, March 1, 2014

PhoneGap Calculator

A lot of beginning PhoneGap developers have asked me if I had a simple PhoneGap tutorial. They didn't want anything complicated. No Backbone, no jQuery Mobile, no ChocolateChip-UI, just plain old HTML, CSS, and JavaScript. So I brought back one of my favorite tutorials, a calculator, stripped it down almost to the bare metal.

I designed this calculator to be reminisce of the one included in the iPhone. In order to get the look of the iPhone's Helvetica Neue font, I used Google Font's Source Sans Pro Extra Light. If you would like to include Google Font's in your app, please check out my post: Using Google Fonts in a PhoneGap App

There is only one complicated part of this app, the ready.js file. In order to make sure that I don't let the app start fully running until both the Cordova "deviceready" and the jQuery "document ready" events have fired, I use a couple of jQuery Deferred objects to wait until those events have both fired. The code in the poorly named, router.js, calls the resolver's initialize method and once the events have fired the passed anonymous function code runs, which calls the calculator method.

The calculator.js is the heart of the app. It consist of two methods, Display and calculator. The calculator method hooks the keys. It is import here to note that the I am hooking the touchstart event. You don't want want to use the click event. The click will work but it will be slow on many devices including the iPhone. The reason is that the click event will do a wait for about 300 milliseconds while it tries to see if you are going to click it again for a double click. Touchstart on the other hand does no such wait. This will give your calculator a responsive UI. I also call event.preventDefault() and event.stopPropagation() both of these will also provide a boost in performance by keeping code which doesn't need to run from running. 

That's it for now. As always the code is on GitHub for you download and make your own.