RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


iPhone Web Development with Ruby on Rails : Page 2

Leverage the tremendous buzz surrounding the iPhone by customizing your web site with CSS and Ruby on Rails.

Orientation, Orientation, Orientation
The iPhone allows users to browse the web in both portrait and landscape mode. This simple feature could have a dramatic impact on the usability of your web site. First, you might want to craft your CSS so that content, ads, and menus are displayed differently in landscape versus portrait mode. Second, you'll want to use your Ruby code to track which orientation your users prefer.

In the future, Apple may improve the ability of Safari to recognize more widely accepted methods for detecting resized events that are traditionally used by web applications. Until then, you'll need to resort to frequently checking the window size with JavaScript and comparing it to a previously stored value to detect rotations in the iPhone, like this:

currentWidth = 0;
window.setInterval( 'checkMyOrientation()', 200 );

function checkMyOrientation() {
 if (window.innerWidth != currentWidth) {
  currentWidth = window.innerWidth;
  var myOrientation = (currentWidth == 320) ? "upright" : "landscape";
  document.body.setAttribute("orientation", myOrientation);
The above JavaScript snippet creates an event timer, a small piece of code that waits 200 milliseconds before calling the checkMyOrientation() function and then repeats that process every 200 milliseconds. This process is called polling and it's a useful way to make event-based decisions in a browser. Every time you run this function, you're going to compare the window's innerWidth property with your own expectation of the browser width to see if the width has changed. You initialize currentWidth to 0, which sets the initial orientation of the phone. After the orientation changes and your timer fires, you'll recognize the change and set the myOrientation variable to either upright or landscape.

In CSS, you can declare any attribute for a tag. Programmers are not limited to attributes that are recognized by any particular browser. In this example, you’ll be creating an attribute for the body tag, called orientation and specifying it to be the string upright or landscape, depending on the result of the JavaScript. You can swap out content on your page based on the contents of the orientation attribute, as follows:


You can create any type of attribute structure you like—including specific menus or even entire div containers exclusively for the iPhone's different orientations. You do this by adding the orientation attribute to any CSS tag.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date