10+ useful code snippets to develop iPhone friendly websites

by Jean. 72 Comments -

When developing websites, you have to care about different browsers, as well as mobile devices such as iPhones or iPods. In this article, let’s have a look at the 10+ most useful code snippets (Javascript, PHP, CSS, etc) for developing iPhone friendly websites, quickly and efficiently.

Detect iPhones and iPods using Javascript

When developing for the iPhone and the iPod Touch, the first thing we have to do is obviously detect it, so we can apply specific code or styles to it. The following code snippets will detect iPhones and iPods using Javascript, and redirect those users to an iPhone specific page.

if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
    if (document.cookie.indexOf("iphone_redirect=false") == -1) {
        window.location = "http://m.espn.go.com/wireless/?iphone&i=COMR";
    }
}

Source: http://davidwalsh.name/detect-iphone

Detect iPhones and iPods using PHP

Although the previous snippet works great, Javascript can be disabled on the iPhone. For this reason, you may prefer to use PHP in order to detect iPhones and iPods touch.

if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'],'iPod')) {
    header('Location: http://yoursite.com/iphone');
    exit();
}

Source: http://davidwalsh.name/detect-iphone

Set iPhone width as the viewport

How many times did you load a website in your iPhone and it just looked like a thumbnail? The reason of this is that the developer forgot to define the viewport (or didn’t know it existed). The width=device-width statement allows you to define the document width as being the same than the width of the iPhone screen. The two other statements are preventing the page from being scaled, which is useful if you’re developing an iPhone-only website. Otherwise, you can remove those statements.
Defining a viewport is easy: Just insert the following meta in the head section of your html document.

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">

Source: http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/

Insert an iPhone specific icon

When a user adds your page to the home screen, the iPhone will automatically use a screenshot of your website as an icon. But you can provide your own icon, which is definitely better.
Defining a custom iPhone icon is easy: Simply paste the following in the head section of your html document. The image should be 57px by 57px in .png format. You do not need to add the shine or corners, as the iPhone will do that for you automatically.

<rel="apple-touch-icon" href="images/template/engage.png"/>

Source: http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/

Prevent Safari from adjusting text size on rotate

When you rotate the iPhone, Safari adjust text size. If for some reason you’d like to prevent this effect, simply use the following CSS declaration. It has to be inserted in your CSS file.
The -webkit-text-size-adjust is a webkit-only CSS property that allow you to control text adjustment.

html, body, form, fieldset, p, div, h1, h2, h3, h4, h5, h6 {
    -webkit-text-size-adjust:none;
}

Source: http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/

Detect iPhone orientation

Due to the fact that the iPhone allow its users to view a page in both portrait and landscape modes, you may need to be able to detect in which mode the document is being read.
This handy javascript function will detect the current iPhone orientation and will apply a specific CSS class so you can style it your way. Note that in this example, the CSS class is added to the page_wrapper ID. Replace it by the desired ID name (See line 24).

window.onload = function initialLoad() {
    updateOrientation();
}

function updateOrientation(){
    var contentType = "show_";
    switch(window.orientation){
        case 0:
	contentType += "normal";
	break;

	case -90:
	contentType += "right";
	break;

	case 90:
	contentType += "left";
	break;

	case 180:
	contentType += "flipped";
	break;
    }
    document.getElementById("page_wrapper").setAttribute("class", contentType);
}

Source: http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/

Apply CSS styles to iPhones/iPods only

Browser sniffing can be useful, but for many reasons it isn’t the best practice to detect a browser. If you’re looking for a cleaner way to apply CSS styles to the iPhone only, you should use th following. It has to be pasted on your regular CSS file.

@media screen and (max-device-width: 480px){
    /* All iPhone only CSS goes here */
}

Source: http://csswizardry.com/2010/01/iphone-css-tips-for-building-iphone-websites/

Automatically re-size images for iPhones

On recent websites, most images are above 480 pixels wide. Due to the iPhone small size, there’s a strong chance that images will break out of the wrapper area.
Using the following CSS code, you’ll be able to automatically re-size the website images to 100%. As the device max width is 480px, images will never be wider.

@media screen and (max-device-width: 480px){
    img{
        max-width:100%;
        height:auto;
    }
}

Source: http://csswizardry.com/2010/01/iphone-css-tips-for-building-iphone-websites/

Hide toolbar by default

On a small screen such as the iPhone screen, a toolbar is useful but also wastes a lot of space. If you’d like to hide Safari toolbar by default when an iPhone visitor open your website, just implement the following javascript code.

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

Source: http://articles.sitepoint.com/article/iphone-development-12-tips/2

Make use of special links

Do you remember those “mailto” link that were very popular some years ago? This prefix automatically open the default email client used by the person who clicked on it. The iPhone has introduced two similar prefixes, tel and sms, which allows the person who clicked on it to phone or text automatically.
I’m definitely not a fan of those, but maybe that will be useful to you. The only thing you have to do to implement this, is to paste the following anywhere on your html page.

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

Source: http://articles.sitepoint.com/article/iphone-development-12-tips/3

Simulate :hover pseudo class

As no one is using a mouse on the iPhone, the :hover CSS pseudo class isn’t used. Though, using some Javascript you can simulate the :hover pseudo class when the user will have his finger on a link.

var myLinks = document.getElementsByTagName('a');
for(var i = 0; i < myLinks.length; i++){
   myLinks[i].addEventListener('touchstart', function(){this.className = "hover";}, false);
   myLinks[i].addEventListener('touchend', function(){this.className = "";}, false);
}

Once you added the code above to your document, you can start css styling:

a:hover, a.hover {
    /* whatever your hover effect is */
}

Source: http://www.evotech.net/blog/2008/12/hover-pseudoclass-for-the-iphone/

Comments (72) - Leave yours

    • John said:

      The viewport tag doesn’t work on iPhone. It never works. Only way is lengthy stupidly longwinded javascript. Sorry, anyone who’s thinking this will fix your viewport issues, it will never do that. Tried and tested.

  1. Douglas Kelly said:

    Dude I have to say that you always have something I want to know. Nice job on this one. I’m definitely going to link over here in my next blog post.

    Keep up the GREAT work.
    dk
    @mollask

  2. Frank said:

    Thank JB!!! Do you plan a similar article for Android as well? Or can we easily transfer the snippets into android ones?

    Greetings!

    • Jakob E said:

      Don’ use the iPhone emulator (iphonetester.com) it does not act as mobile safari
      and it takes flash too ;)

  3. Inside the Webb said:

    I didn’t even know you could do all of this with JavaScript! I’ll have to figure out a way to design a mobile template for my site, it’ll be awesome to showcase my blog directly on mobile phones.

  4. Xanti SS said:

    You should note that using strstr (PHP function) to find if a particular string is inside another is not recommended, and that the function strpos should be used instead.

    http://php.net/strstr

  5. Minna said:

    Very helpful post! I did notice that for the iPhone, setting the DOCTYPE declaration as one of the mobile profiles changed the resolution initially, though I did add the viewport tag later because this is useful for many other devices. http://en.wikipedia.org/wiki/XHTML_Mobile_Profile

  6. Amber Weinberg said:

    I did my first site for the iPhone a few weeks ago and it was definitely a learning experience. After I finished that site, I went back and made a few tweaks to my own to work better ;)

  7. Alice said:

    There’s also the code that allows your site to be used as a web app, which totally removes the URL bar when launched as an app (you can also pick what color the time/carrier/battery bar is).

    • Alice said:

      ugh, html filtering.
      the “apple-mobile-web-app-capable” and “apple-mobile-web-app-status-bar-style” meta tags, found here: http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html

  8. Most Tweeted Articles by CSS Experts said:

    [...] the topic of Web Design is home to many debates and opinions on best practi… 3 Tweets 10+ useful code snippets to develop iPhone friendly websites When developing websites, you have to care about different browsers, as well as mobile devices [...]

  9. Dentaku » 10+ useful code snippets to develop iPhone friendly websites said:

    [...] 10+ useful code snippets to develop iPhone friendly websites * Detect iPhones and iPods using Javascript * Detect iPhones and iPods using PHP * Set iPhone width as the viewport * Insert an iPhone specific icon * Prevent Safari from adjusting text size on rotate * Detect iPhone orientation * Apply CSS styles to iPhones/iPods only * Automatically re-size images for iPhones * Hide toolbar by default * Make use of special links * Simulate :hover pseudo class aus Delicious/steinhobelgruen  Linkdump       [...]

  10. daniel said:

    It think what Alexander Taubenkorb was trying to say is inserting the iPhone icon should be done like this:

    Or you can just name your icon apple-touch-icon.png and place it in your root directory.
    Nice post though!

  11. Mark Slater said:

    Amazing post ! This would really help the web developers to easily build iPhone friendly websites. The convenience of using special links would provide ample new opportunities, ideas and creative websites for the iphone. Hoping to welcome more such useful codes in the iphone world.

  12. atvs said:

    Making websites for mobile phone surfing is very essential nowadays. This generation started web surfing more through iphones, ipods and other mobile devices. So have it in mind, the next generation will use mobile device more than now for Internet surfing. Make sure that your website having the capability to accept the mobile surfing access.

  13. Priyesh said:

    A very good post. It is very important in today’s fast paced environment to be able to view websites on your phone. Meaning that the ability to create websites for mobile viewing is essential. This post gives you a great insight into building web sites for the iphone.

    • Jamie said:

      Thanks for this very helpful post. These days site developers must always consider the iPhone users market because they’re rapidly increasing in size. I’m just wondering though if you have or plan to write a similar post but this time caters to Android or Blackberry?

  14. Matt said:

    Great post. One of the top things to look for in web design in 2011 is mobile exclusive content. This is a great start to be well on your way to staying up to date. Thanks

  15. Tony said:

    Another piece of the puzzle is solved… Still trying to work out how to get the iPhone to display the same text sizes as normal browsers. It’s tricky!

  16. Joe said:

    Please, please, change the third example to

    to remove the maximum scale constraint. Web developers copy and paste examples and often don’t have time to consider accidental policy like this. Disabling scaling is extremely frustrating to people who want to scale. Scaling does not frustrate anyone capable of using an iOS device without being frustrated by it anyway.

    It is obvious that disabling this feature can only cause pain. It can never help. Please. Please. I’m begging you. I want to stab someone every time I land on a web page that thinks it knows more about user experience than the people who made Safari Mobile. They are always, always, wrong. No human being does this on purpose. They just copy some stuff they found googling around. Please make that stuff they copy more humane.

  17. Mike Irving said:

    Great hints… I’m liking the Home Screen Icon tip… and the font resizing and bar hiding mechanisms are a must.

    The user agent is pretty much a given… you can also use some open source scripts to detect a whole array of mobile devices, client or server side, see: http://detectmobilebrowsers.com/

    Mike.

Leave a Reply

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

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!