{"rowid": 277, "title": "Raising the Bar on Mobile", "contents": "One of the primary challenges of designing for mobile devices is that screen real estate is often in limited supply. Through the advocacy of Luke W and others, we\u2019ve drawn comfort from the idea that this constraint ends up benefiting users and designers alike, from obvious advantages like portability and reach, to influencing our content strategy decisions through focus and restraint. But that doesn\u2019t mean we shouldn\u2019t take advantage of every last pixel of that screen we can snag!\n\nAs anyone who has designed a website for use on a smartphone can attest, there\u2019s an awful lot of space on mobile screens dedicated to browser functions that would be better off toggled out of view. Unfortunately, the visibility of some of these elements is beyond our control, such as the buttons fixed to the bottom of the viewport in iOS\u2019s Safari and the WebOS browser. However, in many devices, the address bar at the top can be manually hidden, and its absence frees up enough pixel room for a large, impactful heading, a critical piece of navigation, or even just a little more white space to air things out.\n\nSo, as my humble contribution to this most festive of web publications, today I\u2019ll dig into the approach I used to hide the address bar in a browser-agnostic fashion for sites like BostonGlobe.com, and the jQuery Mobile framework.\n\nSurveying the land\n\nFirst, let\u2019s assess the chromes of some popular, current mobile browsers. For example purposes, the following screen-captures feature the homepage of the Boston Globe site, without any address-bar-hiding logic in place.\n\nNote: these captures are just mockups \u2013 actual experience on these platforms may vary.\n\n On the left is iOS5\u2019s Safari (running on iPhone), and on the right is Windows Phone 7 (pre-Mango).\n\n BlackBerry 7 (left), and Android 2.3 (right).\n\n WebOS (left), Opera Mini (middle), and Opera Mobile (right).\n\nSome browsers, such the default browsers on WebOS and BlackBerry 5, hide the bar automatically without any developer intervention, but many of them don\u2019t. Of these, we can only manually hide the address bar on iOS Safari and Android (according to Opera Web Opener, Mike Taylor, some discussion is underway for support in Opera Mini and Mobile as well, which would be great!). This is unfortunate, but iOS and Android are incredibly popular, so let\u2019s direct our focus there.\n\nGreat API, or greatest API?\n\nAs it turns out, iOS and Android not only allow you to hide the address bar, they use the same JavaScript method to do so, too (this shouldn\u2019t be surprising, given that they are both WebKit browsers, but nothing expected happens in mobile). However, the method they use is not exactly intuitive. You might set out looking for a JavaScript API dedicated to this purpose, like, say, window.toolbar.hide(), but alas, to hide the address bar you need to use the window.scrollTo method!\n\nwindow.scrollTo(0, 0);\n\nThe scrollTo method is not new, it\u2019s just this particular use of it that is. For the uninitiated, scrollTo is designed to scroll a document to a particular set of coordinates, assuming the document is large enough to scroll to that spot. The method accepts two arguments: a left coordinate; and a top coordinate. It\u2019s both simple and supported well pretty much everywhere. In iOS and Android, these coordinates are calculated from the top of the browser\u2019s viewport, just below the address bar (interestingly, it seems that some platforms like BlackBerry 6 treat the top of the browser chrome as 0 instead, meaning the page content is closer to 20px from the top).\n\nAnyway, by passing the coordinates 0, 0 to the scrollTo method, the browser will jump to the top of the page and pull the address bar out of view! Of course, if a quick call to scrollTo was all we need to do to hide the address bar in iOS and Android, this article would be pretty short, and nothing new. Unfortunately, the first issue we need to deal with is that this method alone will not usually do the trick: it must be called after the page has finished loading.\n\nThe browser gives us a load event for just that purpose, so we\u2019ll wrap our scrollTo method in it and continue on our merry way! We\u2019ll use the standard, addEventListener method to bind the the load event, passing arguments for event name load, and a callback function to execute when the event is triggered.\n\nwindow.addEventListener(\"load\",function() {\n window.scrollTo(0, 0);\n});\n\nFor the sake of preventing errors in those using browsers that don\u2019t support addEventListener, such as Internet Explorer 8 and under, let\u2019s make sure that method exists before we use it:\n\nif( window.addEventListener ){\n window.addEventListener(\"load\",function() {\n window.scrollTo(0, 0);\n });\n}\n\nNow we\u2019re getting somewhere, but we must also call the method after the load event\u2019s default behavior has been applied. For this, we can use the setTimeout method, delaying its execution to after the load event has run its course.\n\nif( window.addEventListener ){\n window.addEventListener(\"load\",function() {\n setTimeout(function(){\n window.scrollTo(0, 0);\n }, 0);\n });\n}\n\nSweet sugar of Christmas! Hit this demo in iOS and watch that address bar drift up and away!\n\nNot so fast\u2026\n\nWe\u2019ve got a little problem: the approach above does work in iOS but, in some cases, it works a little too well. In the process of applying this behavior, we\u2019ve broken one of the primary tenets of responsible web development: don\u2019t break the browser\u2019s default behaviour. This usability rule of thumb is often violated by developers with even the best of intentions, from breaking the browser\u2019s back button through unrecorded Ajax page refreshes, to fancy momentum touch scrolling scripts that can wreak havoc in all but the most sophisticated of devices. In this case, we\u2019ve prevented the browser\u2019s native support of deep-linking to sections of a page (a hash identifier in the URL matching a page element\u2019s id attribute, for example, http://example.com#contact) from working properly, because our script always scrolls to the top.\n\nTo avoid this collision, we\u2019ll need to detect whether a deep link, or hash, is present in the URL before applying our logic. We can do this by ensuring that the location.hash property is falsey:\n\nif( !window.location.hash && window.addEventListener ){\n window.addEventListener( \"load\",function() {\n setTimeout(function(){\n window.scrollTo(0, 0);\n }, 0);\n });\n}\n\nStill works great! And a quick test using a hash-based URL confirms that our script will not execute when a deep anchor is in play. Now iOS is looking sharp, and we\u2019ve added our feature defensively to avoid conflicts.\n\n\n\nNow, on to Android\u2026\n\nWait. You didn\u2019t expect that we could write code for one browser and be finished, right? Of course you didn\u2019t. I mentioned earlier that Android uses the same method for getting rid of the scrollbar, but I left out the fact that the arguments it prefers vary slightly, but significantly, from iOS. Bah!\n\nDifferering from the earlier logic from iOS, to remove the address bar on Android\u2019s default browser, you need to pass a Y coordinate of 1 instead of 0. Aside from being just plain odd, this is particularly unfortunate because to any other browser on the planet, 1px is a very real, however small, distance from the top of the page!\n\nwindow.scrollTo( 0, 1 );\n\nLooks like we\u2019re going to need a fork\u2026\n\nR UA Android?\n\nAt this point, some developers might decide to simply not support this feature in Android, and more determined devs might decide that a quick check of the User Agent string would be a reliable way to determine the browser and tweak the scroll value accordingly. Neither of those decisions would be tragic, but in the spirit of cross-browser and future-friendly development, I\u2019ll propose an alternative.\n\nBy this point, it should be clear that neither of the implementations above offer a particularly intuitive way to hide an address bar. As such, one might be skeptical that these approaches will stick around very long in their present state in either browser. Perhaps at some point, Android will decide to use 0 like iOS, making our lives a little easier, or maybe some new browser will decide to model their address bar hiding method after one of these implementations. In any case, detecting the User Agent only allows us to apply logic based on the known present, and in the world of mobile, let\u2019s face it, the present is already the past.\n\nWriting a check\n\nIn this next step of today\u2019s technique, we\u2019ll apply some logic to quickly determine the behavior model of the browser we\u2019re using, then capitalize on that model \u2013 without caring which browser it happens to come from \u2013 by applying the appropriate scroll distance.\n\nTo do this, we\u2019ll rely on a fortunate side effect of Android\u2019s implementation, which is when you programatically scroll the page to 1 using scrollTo, Android will report that it\u2019s still at 0 because oddly enough, it is! Of course, any other browser in this situation will report a scroll distance of 1. Thus, by scrolling the page to 1, then asking the browser its scroll distance, we can use this artifact of their wacky implementation to our advantage and scroll to the location that makes sense for the browser in play.\n\nGetting the scroll distance\n\nTo pull off our test, we\u2019ll need to ask the browser for its current scroll distance. The methods for getting scroll distance are not entirely standardized across popular browsers, so we\u2019ll need to use some cross-browser logic. The following scroll distance function is similar to what you\u2019d find in a library like jQuery. It checks the few common ways of getting scroll distance before eventually falling back to 0 for safety\u2019s sake (that said, I\u2019m unaware of any browsers that won\u2019t return a numeric value from one of the first three properties).\n\n// scrollTop getter\nfunction getScrollTop(){\n return scrollTop = window.pageYOffset ||\ndocument.compatMode === \"CSS1Compat\" && document.documentElement.scrollTop ||\ndocument.body.scrollTop || 0;\n}\n\nIn order to execute that code above, the body object (referenced here as document.body) will need to be defined already, or we\u2019ll risk an error. To determine that it\u2019s defined, we can run a quick timer to execute code as soon as that object is defined and ready for use.\n\nvar bodycheck = setInterval(function(){\n if( document.body ){\n clearInterval( bodycheck );\n //more logic can go here!!\n } \n}, 15 );\n\nAbove, we\u2019ve defined a 15 millisecond interval called bodycheck that checks if document.body is defined and, if so, clears itself of running again. Within that if statement, we can extend our logic further to run other code, such as our check for the scroll distance, defined via the variable scrollTop below:\n\nvar scrollTop,\n bodycheck = setInterval(function(){\n if( document.body ){\n clearInterval( bodycheck );\n scrollTop = getScrollTop();\n } \n}, 15 );\n\nWith this working, we can immediately scroll to 1, then check the scroll distance when the body is defined. If the distance reports 1, we\u2019re likely in a non-Android browser, so we\u2019ll scroll back to 0 and clean up our mess.\n\nwindow.scrollTo( 0, 1 );\n\nvar scrollTop,\n bodycheck = setInterval(function(){\n if( document.body ){\n clearInterval( bodycheck );\n scrollTop = getScrollTop();\n window.scrollTo( 0, scrollTop === 1 ? 0 : 1 );\n } \n}, 15 );\n\nCashing in\n\nAll of the pieces are written now, so all we need to do is combine them with our previous logic for scrolling when the window is loaded, and we\u2019ll have a cross-browser solution of which John Resig would be proud. Here\u2019s our combined code snippet, with some formatting updates rolled in as well:\n\n(function( win ){\n\tvar doc = win.document;\n\n\t// If there\u2019s a hash, or addEventListener is undefined, stop here\n\tif( !location.hash && win.addEventListener ){\n\t\t//scroll to 1\n\t\twindow.scrollTo( 0, 1 );\n\t\tvar scrollTop = 1,\n\t\t\tgetScrollTop = function(){\n\t\t\t\treturn win.pageYOffset || doc.compatMode = \"CSS1Compat\" && doc.documentElement.scrollTop || doc.body.scrollTop || 0;\n\t\t\t},\n\t\t\t//reset to 0 on bodyready, if needed\n\t\t\tbodycheck = setInterval(function(){\n\t\t\t\tif( doc.body ){\n\t\t\t\t\tclearInterval( bodycheck );\n\t\t\t\t\tscrollTop = getScrollTop();\n\t\t\t\t\twin.scrollTo( 0, scrollTop = 1 ? 0 : 1 );\n\t\t\t\t}\t\n\t\t\t}, 15 );\n\t\twin.addEventListener( \u201cload\u201d, function(){\n\t\t\tsetTimeout(function(){\n\t\t\t\t\t//reset to hide addr bar at onload\n\t\t\t\t\twin.scrollTo( 0, scrollTop === 1 ? 0 : 1 );\n\t\t\t}, 0);\n\t\t} );\n\t}\n})( this );\nView code example\n\nAnd with that, we\u2019ve got a bunch more room to play with on both iOS and Android.\n\n\n\nBreak out the eggnog\n\n\u2026because we\u2019re not done yet! In the spirit of making our script act more defensively, there\u2019s still another use case to consider. It was essential that we used the window\u2019s load event to trigger our scripting, but on pages with a lot of content, its use can come at a cost. Often, a user will begin interacting with a page, scrolling down as they read, before the load event has fired. In those situations, our script will jump the user back to the top of the page, resulting in a jarring experience.\n\nTo prevent this problem from occurring, we\u2019ll need to ensure that the page has not been scrolled beyond a certain amount. We can add a simple check using our getScrollTop function again, this time ensuring that its value is not greater than 20 pixels or so, accounting for a small tolerance.\n\nif( getScrollTop() < 20 ){\n //reset to hide addr bar at onload\n window.scrollTo( 0, scrollTop === 1 ? 0 : 1 );\n}\n\nAnd with that, we\u2019re pretty well protected! Here\u2019s a final demo.\n\nThe completed script can be found on Github (full source: https://gist.github.com/1183357 ). It\u2019s MIT licensed. Feel free to use it anywhere or any way you\u2019d like!\n\nYour thoughts?\n\nI hope this article provides you with a browser-agnostic approach to hiding the address bar that you can use in your own projects today. Perhaps alternatively, the complications involved in this approach convinced you that doing this well is more trouble than it\u2019s worth and, depending on the use case, that could be a fair decision. But at the very least, I hope this demonstrates that there\u2019s a lot of work involved in pulling off this small task in only two major platforms, and that there\u2019s a real need for standardization in this area.\n\nFeel free to leave a comment or criticism and I\u2019ll do my best to answer in a timely fashion.\n\nThanks, everyone!\n\nSome parting notes\n\nI scream, you scream\u2026\n\nAt the time of writing, I was not able to test this method on the latest Android 4.0 (Ice Cream Sandwich) build. According to Sencha Touch\u2019s browser scorecard, the browser in 4.0 may have a different way of managing the address bar, so I\u2019ll post in the comments once I get a chance to dig into it further.\n\nShort pages get no love\n\nToday\u2019s technique only works when the page is as tall, or taller than, the device\u2019s available screen height, so that the address bar may be scrolled out of view. On a short page, you might work around this issue by applying a minimum height to the body element ( body { min-height: 460px; } ), but given the variety of screen sizes out there, not to mention changes in orientation, it\u2019s tough to find a value that makes much sense (unless you manipulate it with JavaScript).", "year": "2011", "author": "Scott Jehl", "author_slug": "scottjehl", "published": "2011-12-20T00:00:00+00:00", "url": "https://24ways.org/2011/raising-the-bar-on-mobile/", "topic": "design"}