Learn How To Develop For The iPhone
Today I’m going to show you how to build an alternate page and style sheet for the iPhone and iTouch. We will cover how to detect if the user is using an iPhone to view your page as well as the orientation of the device – whether it be landscape or portrait. To accomplish this we will be using javascript, and some Safari mobile specific CSS tags.
Getting Started
We’re going to start off with 2 psd’s I made and get those working in an iPhone page. I am using images for the background and header although you could use just straight colors instead of images. The plus side to not using images is that it obviously loads faster but also when switching between landscape and portrait the images take a moment to load, depending on how large they are. You can find the source psd files here or you can make your own. Something to keep in mind is that we are building a page specifically for the iPhone or iTouch. If you do not have the device yourself you can download the iPhone SDK freely from Apple and it includes an iPhone simulator. if you would like to detect the iPhone on your standard browser page and either load the iPhone css and html through conditional statements or send the user to a different page entirely, use the following code:

<script type="text/javascript">
var browser=navigator.userAgent.toLowerCase();
var users_browser = ((browser.indexOf('iPhone')!=-1);
if (users_browser)
{
document.location.href='www.yourdomain.com/iphone_index.html';
}
</script>
The code above explained:
- Line 2: Create a variable that holds the users type of browser ( among other things )
- Line 3: Assign the browser type a value if the iPhone browser is present.
- Line 4 – 8: An if statement that redirects the user to an “iPhone formated page” if the variable “users_browser” returns a value ( meaning the user is using an iPhone or iTouch to view the current page ).
Below the code will use html conditional statements to hide the code from a regular browser.
<!--#if expr="(${HTTP_USER_AGENT} = /iPhone/)"-->
<!--
place iPhone code in here
-->
<!--#else -->
<!--
place standard code to be used by non iphone browser.
-->
<!--#endif -->
Step 1: The HTML
So we now know how to point the user to your iPhone page if they are on an iPhone or iTouch device. Now, we will start working on the iPhone HTML page; the code below has some key differences from a regular XHTML transitional document.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"> <title>My iPhone Page</title> <link rel="apple-touch-icon" href="images/myiphone_ico.png"/> <link rel="StyleSheet" href="css/iphone_portrait.css" type="text/css" media="screen" id="orient_css">
The code above explained line by line:
- Line 1 – 5: This is standard 1.0 XHTML Transitional Doctype. Nothing special yet.
- Line 6: This line is iPhone and iTouch specific. It sets initial values for the viewport in the Device’s browser. width=device-width states the width of the page to be the same width of the device. initial-scale and maximum scale set the starting point for the zoom of the page, maximum-scale is how much the page cane be scaled up.
- Line 9: This link element is pointing to the web pages icon. this is used when a user saves the page to their “Home Screen”.
- Line 10: A link element points to the iPhone style sheet. This element has the id orient_css assigned to it. This is so that we can point to it with javascript to change the css file it points to when it comes to adjusting the layout for the orientation of the device.
Step 2: Laying Out The Divs
We now continue with the rest of the html before we add any javascript functions for orientation detection. Start with ending the head and then start the body. In the body element we add onorientationchange=orient();. So I just lied, that is a bit of javascript, but this is needed to call our “orient” function (we’ll go over this in a bit) when ever the device detects a different orientation.
</head> <body onorientationchange="orient();"> <div id="wrap"> <div id="header"> </div> <div id="content"> <p>This is the main content area of the page. </p> <p>Using css and javascript we can manipulate any of these divs using an alternate css file. The css files in this project are for landscape and portrait views.</p> <p>Some more filler text here to demonstrate the page.</p> </div> <div id="bottom"> </div> </div> </body> </html>
Step 3: The Orientation Javascript
In the head of the page you will want to place the code seen below
<script type="text/javascript">
function orient()
{
switch(window.orientation){
case 0: document.getElementById("orient_css").href = "css/iphone_portrait.css";
break;
case -90: document.getElementById("orient_css").href = "css/iphone_landscape.css";
break;
case 90: document.getElementById("orient_css").href = "css/iphone_landscape.css";
break;
}
}
window.onload = orient();
</script>
switch(window.orientation) works off of the onorientationchange() method in the body element. This will check to see if the current rotation is equal to the “case value”, if it returns true it will execute what is after the colon. After an orientation has been matched it breaks out of orient();. window.onload() runs the orient function when the page first finishes loading.
After each case (value) : we have javascript pointing to the link elements id that our css file is attached to. Depending on the case value, 0, 90 or -90 ( there is also 180 but it is not supported on the iPhone at this time) the portrait or landscape css file is attached to the href tag in the link element. 0 is upright (portrait), 90 is landscape counter clockwise. -90 is landscape turned clockwise and 180 although not supported yet would represent the device being upside down.
Step 4: Implementing The CSS
Even with all of this code, the page doesn’t do much. That’s because we need to add background images and style it all. We will create 2 css files, one called iphone_portrait.css and another called iphone_landscape.css. We will place the portrait css file into the link element as the default css file to use.
body
{
background-color:#333;
margin-top:-0px;
margin-left:-0px;
}
#wrap
{
overflow:auto;
width:320px;
height:480px;
}
#header
{
background:url(../images/header.jpg);
background-repeat:no-repeat;
height:149px;
}
#content
{
background:url(../images/middle.jpg);
background-repeat:repeat-y;
margin-top:-5px;
}
p
{
margin:5px;
padding-left:25px;
width:270px;
font-size:10px;
font-family:arial,"san serif";
}
#bottom
{
background:url(../images/bottom_corners.jpg);
background-repeat:no-repeat;
height:31px;
margin-top:-5px;
}
The above code is for the iphone_portrait.css file and is rather straight forward. Some things to note are:
- in the wrap style description overflow:auto makes sure floated items are kept inside the wrap div to keep the page nice and tidy.
- the dimensions for the page are 320px wide by 480px tall. be sure to state this in the wrap div.
Below is the code to be placed inside the iphone_landscape.css file. the only differences between portrait and landscape css files are the background images, the wrap dimensions are reversed and the margins are adjusted accordingly.
body
{
background-color:#333;
margin-top:-0px;
margin-left:-0px;
}
#wrap
{
overflow:auto;
width:480px;
height:320px;
}
#header
{
background:url(../images/l_header.jpg);
background-repeat:no-repeat;
height:120px;
}
#content
{
background:url(../images/l_middle.jpg);
background-repeat:repeat-y;
margin-top:-5px;
}
p
{
margin:5px;
padding-left:25px;
width:370px;
font-size:10px;
font-family:arial,"san serif";
}
#bottom
{
background:url(../images/l_bottom_corners.jpg);
background-repeat:no-repeat;
height:37px;
margin-top:-5px;
}
If you are using my sliced background images your page should now look like the image below when in portrait mode.

Or, in landscape mode?

Where To Go From Here?
So now that you have a page formatted and styled for the iPhone and iTouch, what else can you do? Well, if your page is meant to be more of a web app you may want to check out the IUI by Joe Hewitt which is a framework that makes your pages look like native iPhone or iTouch apps. Also keep in mind that you can set 3 specific css files; so you can have one css file that styles the page if its turned clockwise to landscape and a different file again for when its turned counter clockwise to landscape. This will allow for some interesting outcomes. Good luck!






srry this script:
# <!–#if expr="(${HTTP_USER_AGENT} = /iPhone/)"–>
#
# <!–
# place iPhone code in here
# –>
#
# <!–#else –>
#
# <!–
# place standard code to be used by non iphone browser.
# –>
# <!–#endif –>
Got a question about the iPhone? Ask away. Think you can Answer any question about the iPhone?? Lets see. http://www.iPhoneAnswers.org
Thanks for this article! I’m actually just getting into iPhone-optimized web site design more deeply and this article is very useful.
I wrote some very lightweight JavaScript and PHP code for web site owners to detect mobile devices. The code is available for free download!
- JavaScript: http://www.hand-interactive.com/resources/detect-mobile-javascript.htm
- PHP Code: http://www.hand-interactive.com/resources/detect-mobile-php.htm
Download the code and follow the simple instructions. You can detect as broadly (Is this a smartphone class device?) or as narrowly (Is this an iPod Touch?) as you need.
So take a look at the code and see if it helps you better meet the needs of your web site visitors!
Cheers,
Anthony Hand
Mobile User Experience Designer
thanks dude, used your css with my home security/monitoring system. looks great on my iphone now
This articles is very useful! I have tried it on my Iphone and the site fits well!
One can test thr sites on http://iphonetester.com/
Can you incorporate wordpress or some kind of blogging feature with this?
Wordpress has a FREE iPhone app so you’ll want to use that.
excellent!!
thanks , this is a very good tutorial.
Thanks, It’s really nice informative post. I was looking for the same
This is great but how do you create sliding pages. or links to secondarypages?
how to detct touch for zoom in or zoom out?
great article, hanks
thanks for this tutorial, but I am looking for a somthing which can load a new HTML document after rotate iphone, so it will work on the same idea as above but change the filepath not the css style document.
Anyone has an idea?
Thanks a lot.
I have my page done, on the page is a link to call a phone #. This works fine unless you are on an iPod Touch. what code can I add to make a dialogue box pop up telling the user that they are on an iPod and not an iPhone? Here is what i have so far:
#
Thanks!
that code didn’t take above-
#
Hello
Thank you for this website! Here is mine http://motrin.wikidot.com/
For some reason I cannot get the redirect to work. I copied and pasted your code at the beginning and it’s not working. Am I missing something here? Also, do I need to put the detection code within the conditional statements? Or is that optional?
Thanks for the post, I have been roaming web for this tutorial. thanks a million again.
The redirect is not working for me either!
dreamweaver is telling me i’ve got a syntax error in this line
var users_browser = ((browser.indexOf(’iphone’)!=-1);
I’ve tried every other syntax… is this the problem?
know what? It didn’t help me. I was looking for a solution where the iphone load different css on each portrait (portrait and landscape) it didnt load the css on the fly (tilt) it needs a refresh.
But “Jay Salvat” solution just works fine. Thanks for the tutorial.
on http://www.testiphone.com/ your demo has a problem
the pic is at http://hi.baidu.com/zjm1126/album/item/0df431d4ef85642da08bb72a.html
Interesting, i am currently writing a system that needs to detect whether is an iphone or uses wap and send the user to the appropriate page. We are developing interactive novels for mobile phones in the UK. Check our site: http://www.mifiction.co.uk, we go live in febuary next year
nice tutorial, i am facing an issue, we have a page which is making use of the user name and pwd sent by the end user, and sends it to an AJAX javascript compoenent, which generates the authentication header parameter like this :
var auth = make_basic_auth(document.forms["loginform"].username.value,document.forms["loginform"].password.value);
req.setRequestHeader(‘Authorization’, auth);
The AJAX runs fine when tested on a normal browser, but on iphone gives an error HTTP Authentication is required. Can you please suggest how can we pass http authentication on iphone web app
This guy found that the iPhone is stripping out the ‘Authorization’ header. He changed it to ‘Auth’ and it wasn’t stripped out.
http://www.devilx.net/2009/10/23/iphone-safari-and-xmlhttprequest-authorization-headers/
This redirect didn’t work for me either… I replaced the javascript in the tutorial with:
if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
if (document.cookie.indexOf(“iphone_redirect=false”) == -1) window.location = “http://www.YOURDOMAIN/iphone_index.html”;
}
And it worked.