In the last week, I stumbled across a few mobile sites that hide the iPhone's Safari browser toolbar on page load. In other words, the little address bar at the top of the browser disappears (automatically scrolls up) once the page finishes loading. I did a little research to figure out how this worked, and discovered that a simple JavaScript one-liner can take care of this for you:
window.scrollTo(0,1);
According to this post on iPhone Microsites, window.scrollTo(0,1) is the officially documented method for hiding the iPhone toolbar. On my mobile blog portal at http://mark.kolich.mobi I added this JavaScript one-liner, and sure enough, it does work! Here's a before and after screenshot (yes, this is a screenshot from an emulator, not an actual iPhone).
Continue reading for some additional HOWTO details ...
1 - Front end
On the front end, I added the window.scrollTo(0,1) to my mobile JavaScript onload event listener as shown here:
if (!window.Kolich) {
Kolich = {};
}
Kolich.Mobile = {};
Kolich.Mobile.init = function(){
window.scrollTo(0,1);
}
if(window.addEventListener){
window.addEventListener('load', Kolich.Mobile.init, false);
}else if(window.attachEvent){
window.attachEvent('onload', Kolich.Mobile.init);
}When the mobile page loads, the browser will call my init() function which calls window.scrollTo(). Note that I name spaced my JavaScript a bit for readability, but you don't have to. The window.scrollTo() call will work anywhere as long as it's called once the browser is finished rendering the page.
2 - Back end
On the back end, I'm serving up my mobile blog portal with PHP. Generally speaking, you don't necessarily want to trigger the window.scrollTo() function call in non iPhone web-browsers. So, I configured my PHP to only serve up the iPhone JavaScript above if the HTTP User-Agent is that of an iPhone:
<?php
// True if we detect an iPhone, false if not.
$iPhone = (stristr($_SERVER['HTTP_USER_AGENT'],"iphone")!==FALSE);
// If we detect an iPhone, then source the iPhone JavaScript
// into the rendered page content.
if( $iPhone ){
?> <script type="text/javascript" src="/lib/iphone.js"></script> <?
}
?>
Enjoy.


Did you find this post helpful, or at least, interesting?