iPhone Development: 12 Tips To Get You Started

Maybe you are not a web developer now. You may be also wondering what does “View Source” mean and how you can create sites and apps for your iPhone. Below are some tips that can do you a favour.

1: Documentation and the iPhone Simulator

“Documentation: none,” proclaimed Peter-Paul Koch when he started playing with Safari for iPhone—but the situation has changed since then. Apple now makes iPhone-specific web development information available as part of the Safari documentation.

The iPhone SDK (software development kit), which is Mac-only, also contains an iPhone simulator—this is very handy if you already own an iPhone, and of course it’s absolutely essential if you’re yet to join the iPhone army. To access it, you’ll need to register as an iPhone developer, and install the iPhone SDK. Once you’ve installed it, you’ll find the iPhone simulator in/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications.

2: Small Screen CSS

The most obvious difference between an iPhone and your PC or Mac is that the iPhone has a much smaller screen. If you already have a page that works in desktop browsers and screen readers, one simple strategy is to have an additional style sheet that’s only used by the iPhone. Here’s the markup you’d use:

<!--[if !IE]>-->
media="only screen and (max-device-width: 480px)"

This link element uses a media query to target devices with a maximum width of 480 pixels—that is, the available width when the iPhone is in landscape orientation.The IE conditional comments are needed for IE version 5.5 or earlier; these versions lack support for the media query and will load the style sheet intended for the iPhone. Let’s try an example.

In Example 1, we can see a page that will display a red box to iPhone viewers, and a blue one to other viewers. A style sheet, common.css, contains styles intended for all browsers, including the declaration for the blue box. Another, small-screen.css, is intended for handheld devices and contains the declarations for the red box. When you load this example in an iPhone, you’ll see the red box; on your desktop, you’ll see blue.

If you’d prefer to use only one style sheet, you could add the iPhone-only styles to the main style sheet using an @media block, like so:

@media only screen and (max-device-width: 480px) {
#test-block {
background: red;

We can see an example of an inline stylesheet in use in Example 2. In the stylesheet it uses, onestyleforall.css, you’ll see the declaration for a red background in an@media block.

3: The Viewport Meta Element

By default, Safari on the iPhone will render your page as if it was a desktop browser on a big screen, with 980 pixels width available for the web content. Then it will scale down the content so that it fits the small screen. As a result, the user sees your page with miniscule, illegible letters and must zoom in to see the interesting parts. This might be okay for your web pages, but if you’re designing a web app that aims to look like a native application, this is unacceptable.

Luckily, this is easy to correct using the special viewport meta element:

<meta name="viewport" content="width=device-width" />

This element instructs the browser to use the width of the device as the width of the viewport, instead of the default 980 pixels. We can see the difference with two examples.

  1. Example 3 shows a simple paragraph element and no viewport meta element. The font is almost unreadable.
  2. Example 4 includes the viewport element. Now that the device width is only 320 pixels, the font size is much easier to see.

Alternatively, you can set a device-width value to any number you like. For example, let’s say your blog has a layout with a fixed width of 750 pixels, so that it fits nicely in an 800×600 desktop screen. Example 5 shows a stripped-down version of this kind of layout: if you load it in the iPhone, you’ll see white space that fills up the rest of the 980 pixels.

To eliminate the extra space, you can use the viewport meta element and set the width to 780px: <meta name=”viewport” content=”width=780″ />

Example 6 shows a version of our fixed layout with this viewport meta element.

The content of the meta viewport element can also contain multiple comma-delimited values, such as initial-scale—the zoom level at which the user initially sees your page—as well as whether the interface is user-scalable. For web apps, a common set of values is:

<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />

This element sets the width to the maximum device width (as we saw before), zooms into a zoom level of one, and also forbids the user to zoom in and out of the content. That’s handy for web apps that should look and feel like a native application.

4: Orientation Changes

Your pages and apps can be viewed in two orientation modes: portrait and landscape. It could be useful for your app to react to changes in the orientation.

Using JavaScript you can access the property window.orientation, which can have these values:

  • 0—normal portrait orientation (home button is at the bottom)
  • -90—landscape after clockwise rotation from portrait (home button to the left)
  • 90—landscape after counterclockwise rotation from portrait (home button to the right)
  • 180—unsupported for now, but would be portrait-flipped so that the home button is at the top

There’s also the orientationchange event you can use to perform an action when the user tilts the device. Here’s an example that simply presents an alert whenever the orientation changes, displaying the window.orientation value:

window.onorientationchange = function() {

You can see how this works in Example 7: rotate the phone to see the alerts. In the iPhone simulator, you’ll find the option to rotate the device under the Hardware menu.

5: Orientation-specific Styles

Let’s put that orientation change event to a more practical use. Sometimes you might need to format your content using styles that depend on the orientation. This will require three simple steps:

  1. in our markup, add a class name to the body element (portrait and landscape are as good as any!)
  2. in our stylesheet, specify different content styles for body.portrait and body.landscape, as well as any descendant elements that may require it
  3. use JavaScript to update the value of the body element’s class attribute when the orientation changes

So the first step is to add a default class name, like so:


Then the styles can be added:

body.portrait p {
color: red;

body.landscape p {
color: blue;

And finally, the JavaScript. We’ll need to use:

  1. a listener for the load event to set the class name initially
  2. another listener for the orientationchange event
  3. a function to swap the class name when the orientationchange event occurs

Let’s take a look at the event listeners:

window.addEventListener('load', setOrientation, false);
window.addEventListener('orientationchange', setOrientation, false);

And here’s a setOrientation function that changes the class name on the body element:

function setOrientation() {
var orient = Math.abs(window.orientation) === 90 ? 'landscape' : 'portrait';
var cl = document.body.className;
cl = cl.replace(/portrait|landscape/, orient);
document.body.className = cl;

Example 8 shows these orientation specific styles.

6: Hide Toolbars

You may have noticed that when a page is first loaded on an iPhone, the URL toolbar is visible, and when you scroll down a page, the URL toolbar disappears.

If you’d like to make your web application feel more like a native iPhone application, you’ll want to remove the toolbar right away when the page loads. To do this, simply scroll the page one pixel down, using window.scrollTo:

window.addEventListener('load', function(){
setTimeout(scrollTo, 0, 0, 1);
}, false);

Example 9 shows this behaviour.

What happens if your page is too short to become scrollable? We’ll need an additional meta element in case that occurs. In order to make the page scrollable, we can set the height of the viewport using the meta element:

<meta name="viewport" content="height=device-height,width=device-width" />

7: Rounded Corners

You have to have rounded corners, right? You can use your favorite rounded-corners approach that works across the major desktop browsers, or, if you target only Safari, you can benefit from the -webkit-border-radius CSS extension. Since there’s a similar -moz-border-radius for Firefox, you can have a nice, rounded element in Firefox and Safari, which will degrade nicely to a simple box in IE and Opera:

.box {
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
background: #ddd;
border: 1px solid #aaa;

Example 10 shows these easy rounded corners on a div element.

8: Touch Events

Of course, you use your iPhone with a finger instead of a mouse; rather than clicking, you tap. What’s more, you can use several fingers to touch and tap. On the iPhone, mouse events are replaced by touch events. They are:

  • touchstart
  • touchend
  • touchmove
  • touchcancel (when the system cancels the touch)

When you subscribe to any of those events, your event listener will receive an event object. The event object has some important properties, such as:

  • touches—a collection of touch objects, one for each finger that touches the screen. The touch objects have, for example, pageX and pageYproperties containing the coordinates of the touch within the page.
  • targetTouches—works like touches, but only registers touches on a target element as opposed to the whole page.

The next example is a simple implementation of drag and drop. Let’s put a box on a blank page and drag it around. All you need to do is subscribe to thetouchmove event and update the position of the box as the finger moves around, like so:

window.addEventListener('load', function() {

var b = document.getElementById('box'),
xbox = b.offsetWidth  / 2, // half the box width
ybox = b.offsetHeight / 2, // half the box height
bstyle = b.style; // cached access to the style object

b.addEventListener('touchmove', function(event) {
event.preventDefault(); // the default behaviour is scrolling
bstyle.left =  event.targetTouches[0].pageX - xbox + 'px';
bstyle.top  =  event.targetTouches[0].pageY - ybox + 'px';
}, false);

}, false);

The touchmove event listener first cancels the default behavior of the finger move—otherwise Safari will scroll the page. The collection event.targetTouchescontains a list of data for each finger currently on the target div element. We only care about one finger, so we use event.targetTouches[0]. Then pageXgives us the X coordinate of the finger. From this value we subtract half the width of the div so that the finger stays in the center of the box.

We’ve put all that code together in Example 11.

9: Gestures

On the iPhone, gestures are two-finger actions: scaling (zoom in and zoom out) and rotation. We learned above that the touches and targetTouches events contain information about each finger that touches the device. It’s possible to use those events to also handle gestures such as zoom and pan. But for this purpose, there are more convenient gesture events. You can listen to the following events:

  • gesturestart
  • gestureend
  • gesturechange

In the next example, we’ll listen to the gesturechange event, and then scale and rotate a div using the WebKit-only webkitTransform style property. As usual, the event listeners accept an event object parameter. The event object has the properties:

  • event.scale—a value of 1 when there’s no scaling, less than 1 when zooming out (such as making our div smaller), and greater than 1 when zooming in.
  • event.rotate—the rotation angle in degrees.

The code is very similar to the touch-and-drag code from the previous example:

window.addEventListener('load', function() {
var b = document.getElementById('box'),
bstyle = b.style;
b.addEventListener('gesturechange', function(event) {
bstyle.webkitTransform = 'scale(' + event.scale + ') ' +
'rotate('+ event.rotation + 'deg)';
}, false);
}, false);

Example 12 shows this code in action—scaling and rotating a div.

If you’re viewing that example in an iPhone simulator, hold down the Option key: two gray dots will appear to represent two fingers, and as you drag the mouse, you can move the dots in and out.

10: Special Links

It’s nice when you browse a page that has a phone number to be able to simply click and call the number without typing it out. Phone numbers become links automatically provided, of course, they follow a phone number format. But there might be cases when you want to create the phone links manually. In this case you can use the tel: prefix (URI scheme), for example:

<a href="tel:12345678900">Call me</a>

If an SMS text is more your style, use the sms: scheme to launch the iPhone’s text message application.

<a href="sms:12345678900">Send me a text</a>

Some other links can perform special actions on the iPhone, although a special URI scheme is unnecessary:

  • Links to the iTunes Store will launch iTunes. You can obtain the link to a track in the iTunes Store by using iTunes to search for the track, then right-clicking on the result, and selecting “Copy iTunes Store URL.” Another way is to use the iTunes Link Maker application, which generates the HTML markup to use, including a nice little iTunes button graphic.
  • A link to Google Maps will launch the Maps application.
  • YouTube links will launch the native YouTube application, as opposed to the YouTube site.
  • Links to an email address will launch the Mail application.
11: The Home Icon

Hopefully a visitor will like your site so much that they think it deserves a spot on their Home screen. When a user adds your page to the Home screen, the iPhone will use a screenshot of your page as an icon. But you can do better by providing your own icon.

To do this, create a PNG file with dimensions 57x57px, name it apple-touch-icon.png, and put it in the root of your web server, just like you would with a favicon—and you’re done. The iPhone will automatically add the glossy effect and rounded corners—no need to try to recreate this on your own!

You also have the flexibility of specifying the location and the filename of the icon, via a link element. This allows you to use a different web server, such as a content distribution network (CDN), to host the icon or share the same file across several web sites. To specify the location of the icon, use a link element as follows:

<link rel="apple-touch-icon" href="http://www.example.com/my-filename.png" />

12: Debugging: View Source and the Console

How about viewing the source—the all-time favorite learning and debugging tool? This is unavailable on the iPhone. Luckily, bookmarklets work in Safari for the iPhone, so you can use bookmarklets to add missing functionality. How do you do that?

Well, you have access to the source of the page (generated source, that is) in JavaScript via document.documentElement.innerHTML. In your bookmarklet it’s only a question of displaying this somehow, for example, in a new window. But the good news is that this JavaScript exercise can be performed by a nicely working bookmarklet. iPhoneWebDev has already packaged up some bookmarklets, optimized for the iPhone display and free for the taking. Once you have the bookmarklets you need, simply synchronise your bookmarks to your iPhone in iTunes.

For debugging, the iPhone includes a debugging console. You can enable it on your phone by going to Safari’s settings in the Settings app, choosing Developer, and setting Debug Console to ON. Now it appears in your Safari browser under the URL toolbar. It will show you any errors you might have on your pages, and you can also use the console object to write any debug messages from your JavaScript. For example:


Go Forth and Develop!

Well, at the end of this intro article I’d like to welcome you to iPhone web development with its new and exciting possibilities and challenges. I hope that by now you have a few ideas of your own and you’re eager to try them out.

This entry was posted in Cell Phone. Bookmark the permalink.

6 Responses to iPhone Development: 12 Tips To Get You Started

  1. Afton Coman says:

    I would like to ask my friend to arrive as well as read this awesome article.

  2. d'angle says:

    Really good job. People should read this.

  3. townhomes says:

    It’s amazing to pay a visit this web site and reading the views of all friends about this article, while I am also zealous of getting familiarity.

  4. jack says:

    This is a really good tip especially to those fresh to the blogosphere.
    Simple but very precise information… Appreciate your sharing this one.
    A must read post!

  5. Pingback: Wynell Mcphillips

  6. Pingback: Luna Counihan