views:

7195

answers:

2

I'm building a iPhone Web Application and want to lock the orientation to portrait mode. is this possible? Are there any web-kit extensions to do this?

Please note this is an application written in HTML and JavaScript for Mobile Safari, it is NOT a native application written in Objective-C.

+5  A: 

You can specify CSS styles based on viewport orientation: Target the browser with body[orient="landscape"] or body[orient="portrait"]

http://www.evotech.net/blog/2007/07/web-development-for-the-iphone/

However...

Apple's approach to this issue is to allow the developer to change the CSS based on the orientation change but not to prevent re-orientation completely. I found a similar question elsewhere:

http://ask.metafilter.com/99784/How-can-I-lock-iPhone-orientation-in-Mobile-Safari

Scott Fox
Thanks but, I'm doing that part already, what I really want is to prevent Mobile Safari to not switch orientation on me when the user tilts the phone.
Kevin
Apple's approach to this issue to to allow the developer to change the CSS based on the orientation change but not to prevent re-orientation completely. I found a similar question elsewhere:http://ask.metafilter.com/99784/How-can-I-lock-iPhone-orientation-in-Mobile-Safari
Scott Fox
Scott - if you copy your latest comment into the answer, I'll mark it as the accepted answer and give you the karma points :)
Kevin
Thanks Kevin! I appreciate it.
Scott Fox
+3  A: 

This is a pretty hacky solution, but it's at least something(?). The idea is to use a CSS transform to rotate the contents of your page to quasi-portrait mode. Here's JavaScript (expressed in jQuery) code to get you started:

$(document).ready(function () {
  function reorient(e) {
    var portrait = (window.orientation % 180 == 0);
    $("body > div").css("-webkit-transform", !portrait ? "rotate(-90deg)" : "");
  }
  window.onorientationchange = reorient;
  window.setTimeout(reorient, 0);
}

The code expects the entire contents of your page to live inside a div just inside the body element. It rotates that div 90 degrees in landscape mode - back to portrait.

Left as an excercise to the reader: the div rotates around its centerpoint, so its position will probably need to be adjusted unless its perfectly square.

Also, there's an unappealing visual problem. When you change orientation, Safari rotates slowly, then the top-level div snaps to 90degrees different. For even more fun, add

body > div { -webkit-transition: all 1s ease-in-out; }

To your CSS. When the device rotates, then Safari does, then the content of your page does. Beguiling!

Grumdrig