having fun with code

Detecting iPhone’s orientation

Detecting the iPhone’s orientation on a website is very easy: the only thing needed is a little bit of Javascript to listen to the onorientationchange event:

  1. window.onorientationchange = function() {
  2.   if (window.orientation)
  3.     document.body.setAttribute('class', 'landscape');
  4.   else
  5.     document.body.setAttribute('class', 'portrait');
  6. }
  7. window.onload = function() {
  8.   window.onorientationchange();
  9. }

The window.orientation variable can have three different values: 0, 90 and -90. In most cases we wont mind if its 90 or -90, since both are landscape, so I have ignored this on the code above. Adding a CSS class to the body is the cleanest way to handle iPhone’s orientation. Now it’s up to you to set up the CSS for both layouts.

The resolution of the visible screen (viewport) changes drastically from portrait to layout, so be aware of this:

  • Portrait visible screen: 320 x 356 px
  • Landscape visible screen: 480 x 196 px

Source: Web Apps Reference Library – Handling Orientation Events (needs registration)

Related Posts:

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info

PromoteJS

JavaScript JS Documentation