This morning I read a post on the Phonegap Google group asking about their support for orientation changes. While PhoneGap has good event support it doesn't support orientation changes. Why? Because there is no need - turns out the mobile browsers support this themselves. It is probably a good idea to remember that your mobile browsers can do quite a bit themselves. If you find something missing from PhoneGap that you think should be included, ensure the browsers just don't support it already. (And if not, check out the excellent list of plugins.)

I did a quick Google and found that both Safari and Android support a simple orientation change event listener. With that I whipped up a quick PhoneGap application. I began with a super simple front end:

    <meta name="viewport" content="width=320; user-scalable=no" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
	  <script type="text/javascript" charset="utf-8" src="phonegap-1.1.0.js"></script>
	  <script type="text/javascript" charset="utf-8" src="main.js"></script>

  <body onload="init();" >
		<h2>Orientation Test</h2>
		<div id="status"></div>


And my code is then just:

function init() {
    window.addEventListener("orientationchange", orientationChange, true);


function orientationChange(e) {
    var orientation="portrait";
    if(window.orientation == -90 || window.orientation == 90) orientation = "landscape";

Two things to notice here.

  1. Notice that I check window.orientation for -90 and 90. Those values represent a landscape view. It also implies you can check for rotating one way versus the other.
  2. My application listens for the change, if you want to know on startup what the current orientation is, just perform the same check. You could abstract out most of orientationChange into getOrientation() and simply call that in you rinit and orientationChange methods.

And here is a quick screen shot of it in action.

p.s. Recently I mentioned a plugin that significantly improves the experience of creating PhoneGap applications in Eclipse. I began having issues with orientation changes crashing the application. On a whim I decided to check and see if a new version of the plugin existed and indeed there was. Updating fixed everything. I still wish the plugin had a way to output an empty HTML file but it's much easier than building things out by hand.