Optimize Your Website for iPhone with CSS and ASP.NET

So the cool thing in web design right now is “optimizing” your website for the iPhone. This is essentially kind of pointless, since the whole idea behind the iPhone’s version of the Safari browser is to be able to view webpages “as is”, so you can see them just as you would on a regular computer, but you can zoom in and out to get a closer look. The “iPhone optimized” version presents the content in a way that zooming is unnecessary, and the user can simply scroll down to view the page. These often take on the style of the iPhone interface itself. I work for a medical association, and many of my members use iPhones, and with the advent of medical apps for the platform, I predict many more will in the future. That, combined with my boredom and the need to find a hobby that does not involve booze, I decided to create a iPhone optimized version of my association’s website.

The popular way to do this is to detect the browser coming into the site and then redirect them to the iPhone optimized material. This is usually a few alternate pages with key information, or a subdomain that mirrors the main content. However, I wanted to give my visitors the choice to flip-flop between the iPhone and screen views. There’s no way in hell I am going to maintain two different versions of the content, so I decided to just create a separate iPhone stylesheet, and then allow the user to choose the view through a form. The whole process only took a day or two and was easily done with CSS and ASP.NET. Once you’ve got your iPhone stylesheet set up, the steps are:

1) Create a form that detects the iPhone and then submits the user’s choice of view
2) A conditional statement in the head that spits out the stylesheet of choice
3) Create an iphone-specific stylesheet
4) The little extras

1) Create the form:

Using ASP.NET, I used the Request.UserAgent to determine if they were on an iPhone and displayed the radio button. Put this in the body where you want it to appear:


<% If Request.UserAgent.IndexOf("iPhone")>-1 or Request.UserAgent.IndexOf("iPod")>-1 Then %>
<p>Insert message to be displayed about changing view.</p>
<asp:RadioButton id="iPhone_view" Text=" iPhone Optimized" GroupName="iPhone" runat="server"/>
<asp:RadioButton id="screen_view" Text=" Screen Optimzed" GroupName="iPhone" runat="server"/>
<asp:Button id="Button1" runat="server" Text="Update View" onClick="Button1_Click" />
<% End If%>

2) Put this up top; it takes the form value and creates a session variable:


<%@ Page Language="vb"%>
<script language="VB" runat="server">
   Sub Button1_Click(ByVal s As Object, ByVal e As EventArgs)
   Session("iPhone_view") = Request("iPhone")
   End Sub
</script>

3) Insert the conditional stylesheet code in the head. This will spit out a certain stylsheet based on the session variable, so you don’t have to deal with mixed tags. Notice that if the “iphone_view” session variable value is present, then it will also output a “viewport” tag, which tells the iphone how to initially display the content, as well as control scaling:


<% If session("iPhone_view") = "" Then
Response.Write("<link rel=""stylesheet"" type=""text/css"" href=""style.css"" media=""Screen"" />")
ElseIf session("iPhone_view") = "iPhone_view" Then
Response.Write("<link rel=""stylesheet"" type=""text/css"" href=""iphone.css"" media=""Screen"" />" & vbCRLF)
Response.Write("<meta content=""initial-scale=1, user-scalable=no"" name=""viewport"">")
ElseIF session("iPhone_view") = "screen_view" Then
Response.Write("<link rel=""stylesheet"" type=""text/css"" href=""style.css"" media=""Screen"" />")
Else 
Response.Write("<link rel=""stylesheet"" type=""text/css"" href=""style.css"" media=""Screen"" />")
End If
%>

4) Now that we’ve got everything set up, we need the alternate stylesheet. Although you can style it any way you want, the most important thing is to set the width to 300px to prevent horizontal scrolling. You can also use cool effects, since it uses webkit. I have inserted a CSS snippet below with the most important stuff – specifically background, the list items with the webkit-border-radius, and break-word. You can also download a zip file that contains a simple stylesheet and images to get you started.


BODY {
	FONT-SIZE: 16px; BACKGROUND-IMAGE: url(background.png); MARGIN: 9px; COLOR: #324f85; FONT-FAMILY: sans-serif, "Arial"; BACKGROUND-COLOR: #c5ccd4
UL {
	BORDER-RIGHT: #acaeb0 1px solid; PADDING-RIGHT: 0px; BORDER-TOP: #acaeb0 1px solid; PADDING-LEFT: 0px; PADDING-BOTTOM: 0px; MARGIN: 0px; BORDER-LEFT: #acaeb0 1px solid; WIDTH: 300px; PADDING-TOP: 0px; BORDER-BOTTOM: #acaeb0 1px solid; LIST-STYLE-TYPE: none; BACKGROUND-COLOR: #ffffff; -webkit-border-radius: 10px
}
LI {
	PADDING-RIGHT: 12px; BORDER-TOP: #acaeb0 1px solid; PADDING-LEFT: 12px; FONT-WEIGHT: bold; PADDING-BOTTOM: 12px; COLOR: #000000; PADDING-TOP: 12px; WORD-WRAP: break-word
}
LI SPAN {
	MARGIN-TOP: -18px; DISPLAY: block; FONT-WEIGHT: normal; WIDTH: 276px; COLOR: #324f85; TEXT-ALIGN: right
}
LI A {
	BACKGROUND-POSITION: right center; DISPLAY: block; BACKGROUND-IMAGE: url(arrow.png); BACKGROUND-REPEAT: no-repeat; TEXT-DECORATION: none
}
LI:first-child {
	BORDER-TOP: medium none
}

5) Add little extras. I added the “iphone favicon”, which will add your graphic to the iPhone’s home screen, and a javascript message that runs once a session (with a cookie) alerting them to the choice in views. The code for both is below:


<link rel="apple-touch-icon" href="iphone-icon.png">

<script type="text/javascript">
//alerts iPhone/iPod Touch users the first time they enter the site about iPhone view
if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
{
var alertmessage="Insert message for iPhone users."

//Alert only once per browser session (0=no, 1=yes)
var once_per_session=1


function get_cookie(Name) {
  var search = Name + "="
  var returnvalue = "";
  if (document.cookie.length > 0) {
    offset = document.cookie.indexOf(search)
    if (offset != -1) { // if cookie exists
      offset += search.length
      // set index of beginning of value
      end = document.cookie.indexOf(";", offset);
      // set index of end of cookie value
      if (end == -1)
         end = document.cookie.length;
      returnvalue=unescape(document.cookie.substring(offset, end))
      }
   }
  return returnvalue;
}

function alertornot(){
if (get_cookie('iPhonealert')==''){
loadalert()
document.cookie="iPhonealert=yes"
}
}

function loadalert(){
alert(alertmessage)
}

if (once_per_session==0)

loadalert()

else
alertornot()

}

</script>

And that’s it! Just put the form, session, and extra code in your home page and the stylesheet code in each page that you want to be able to have the iPhone view and you basically have two complete “sites” without duplicating content. Since the choice of stylesheet is rendered server-side, it only outputs what you want, eliminating the tag confustion of multiple stylesheets, and the session variable will carry the choice from page to page. You can see this in action at http://www.asn-online.org (you need to be using an iPhone or an iPod Touch to view the form). iPhone CSS templates are all over the web, but if you need help with anything, just let me know.

Cheers,

Hal

p.s. – 9/21/2009 UPDATE: So I switched up the radio button toggle with an awesome “iPhone” slider toggle from Giva Labs (jquery plugin). Try it on: http://www.givainc.com/labs/ibutton_jquery_plugin.htm

Published by

Hal

Aside from being a champion yo-yoer, I am the full-time computer geek at the American Society of Nephrology. I recently completed my MBA from George Washington University which I am hoping will enable me to finally afford my own bad habits. I also do freelance design, specializing in Flash, PHP, and ASP/ASP.NET.

2 thoughts on “Optimize Your Website for iPhone with CSS and ASP.NET”

Leave a Reply

Your email address will not be published. Required fields are marked *