This tutorial will outline a simple procedure used to display an “iPhone style” modal prompt whenever a user visits your site from an iPhone/iPod touch. For this example we will combine user agent detection with the JavaScript confirm() method to create a prompt which allows the user to select between your regular and iPhone-optimized versions of your website.
Once they’ve made their selection the user will be forwarded to the appropriate version of your site. The resulting prompt will look like the example to the left. The alert will inherit the default look from the iPhone.
Step 1
Create a function to detect the target device.
<script type="text/javascript">
function iPhoneAlert() {
if((navigator.userAgent.match(/iPhone/i))||(navigator.userAgent.
match(/iPod/i))){
}
}
</script>
Step 2
Extend the function to display a modal prompt upon success.
<script type="text/javascript">
function iPhoneAlert() {
if((navigator.userAgent.match(/iPhone/i))||(navigator.userAgent.
match(/iPod/i))){
var question = confirm(”Would you like to view the iPhone-optimized version of our site?”)
if (question){
window.location = “http://lite.iphonemicrosites.com/home.html”;
}else{
window.location = “http://iphonemicrosites.com/mainsite.html”;
}
}
}
</script>
Step 3
Call the function by adding an onLoad event handler to the body tag.
<body onLoad="iPhoneAlert();">
This tutorial could be further extended to store the user preference in a cookie for future visits.
I’ve also covered a less intrusive method consisting of displaying a custom message on the website itself. Regardless of which method you choose, notifying your visitors of your iPhone Microsite as opposed to forcing them to view it is a good way to enhance your visitors experience.
Please note that user agent detection may not be the best detection solution, and media query may be a more elegant way to solve your needs.
*Edit – If you’re having problems with the above code (it’s quite old), try this code which “homecookin” posted.
<title>iphone</title>
<script type="text/javascript">
function iPhoneAlert( )
{
if ( navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) )
{
var qes = confirm( "Would you like to view iPhone-optimized version of our site?" );
if ( qes )
window.location = "here goes your iphone site url.";
}
}
</script>
And in the body tag
<body onload="iPhoneAlert( );">

