July 5, 2010

Javascript: iPad orientation class with Prototype.js

I'm writing an iPad app in "HTML5", and I wanted to keep track of the device orientation. I wrote this little class to send notifications when it changes, and to always have simple access to the current state. This requires Prototype.js, but could easily be ported to another OOP style.
var AppState = Class.create({
 PORTRAIT: 0,
 LANDSCAPE: 1,
 orientation: -1,    
 initialize: function() {
  this.orientation = this.PORTRAIT; // default for desktop browser
  this.setUpOrientationListener();
 },
 setUpOrientationListener : function() {
  // add listener to window if it's orientation-capable
  if( window.orientation !== undefined )
  {
   var self = this; // handles scope
   window.onorientationchange = function (event)
   {
    if ( Math.abs( window.orientation ) % 180 == 90 )
    {
     self.orientation = self.LANDSCAPE;
    }
    else
    {
     self.orientation = self.PORTRAIT;
    }
    // send out custom event
    var containerNode = $$('body');
    containerNode[0].fire("app:orientationchange", { orientation: self.orientation });
   }
   // make sure local flag is set right away
   window.onorientationchange(null);
  }
 }
});


/*
// example code for listening to custom event that fires on orientation change
document.observe("app:orientationchange", function(event) {
 console.log( "Tag " + event.target.tagName + " with id of " + event.target.id + " says the orientation is now " + event.memo.orientation + ".");
});
*/

/*
// class initialization
var app_state = new AppState(),
*/

4 comments:

  1. I've got an app that pops up a prototype window, which is centered on all browsers, but in the iPad, it ends up being at the top of the original page (not the viewport), instead of centered in the viewport. Have you encountered this?

    ReplyDelete
  2. I haven't, sorry. with all my experiments I'm not sure what might be causing that.

    ReplyDelete
  3. I try to disable orientation change event,
    Is it possible with js?
    Can we do this?

    ReplyDelete
  4. I'm not sure what you mean. This is a callback, so don't listen if you don't want to respond to it. Otherwise, if you don't want the orientation to change, some devices have a hardware lock, but there's no Javascript for that.

    ReplyDelete