Site Meter

Full-height app layouts: Navigation and History

This is the third in a series of posts about web app layouts, i.e., giving your web-based application a UI comparable to a desktop or mobile/tablet app. Posts so far:

  1. Layout basics – A CSS technique for slicing up the browser window into arbitrarily nested panes both horizontally and vertically. You know, like a proper application, and not like an infinite-height document…
  2. Animated transitions – How to put more than one content block into a given pane, and then switch between them with hardware-accelerated animations
  3. This post – Keeping track of what content has appeared in each pane, so the visitor can navigate back and forwards. And supporting deep linking. And injecting new panes dynamically.

Disclaimer: To be clear, this post series just represents my own experiments in lightweight, flexible web app layouts and is not an official part of any Microsoft technology stack. No guarantees or warranties or SLAs, blah blah blah.

The goal

It’s very common on mobile/tablet-like UIs for users to navigate through some structure of content within a given pane. For example, in a tablet-like app, you’ll often want to have a left-hand pane representing navigation through a hierarchy, with the main section of the screen representing the currently selected item or folder:


So, you’ll want to be able to:

  • Keep track of where the user has been, letting them go back and forwards, with each pane able to maintain its own independent history.
  • Perform smooth animated transitions within each pane when any navigation event occurs.
  • Support deep-linking to arbitrary locations in your content structure
  • Fetch and render content dynamically

Basic navigation

Continuing from previous posts that introduced pane hierarchies and panes.js, it’s pretty easy to keep track of where a visitor has been. First you might set up a basic pane layout with a header/body/footer like this:

<div class="page">
    <div class="header row">
        Header will go here
    <div class="body row">
        Body contents will go here
    <div class="footer row">
        My footer. Could put icons here.

… and then put multiple panes into the body row:

<div class="body row">
    <div id="location-continents" class="pane">
            <li><a href="#america">America</a></li>
            <li><a href="#europe">Europe</a></li>
    <div id="location-america" class="pane">
        <h3>Countries in the Americas</h3>
            <li><a href="#canada">Canada</a></li>
            <li><a href="#usa">USA</a></li>
    <div id="location-canada" class="pane">
        <h3>Cities in Canada</h3>
    <!-- ... etc ... -->

Now you can begin history tracking by adding a bit of JavaScript to instantiate a PaneHistory object and navigate to an initial pane:

// Navigation
var paneHistory = new PaneHistory();

… and perform pane navigations each time the visitor clicks on one of the links:

$("a").click(function (evt) { 
    var dest = (evt.srcElement ||"#")[1]; 
    paneHistory.navigate("location-" + dest); 
    return false; 

This code will intercept clicks on the links, figure out which pane they are trying to get to, and then animate that destination pane sliding smoothly into the body area from the right.

If you also want to let the visitor go “back” through the pane’s history stack, add a button perhaps into the page header:

<div class="header row">
    <p><button class="goBack">&lt; Back</button></p>

… and handle clicks by instructing the PaneHistory instance to perform a reverse navigation animation:

$(".goBack").click(function () {

That’s it. Try it out. Live example:

Also: Run full screen (e.g., to try it on a phone)

Supporting the back/forward buttons and deep-linking

If your app will be deployed to the web (as opposed to using something like PhoneGap to package for an appstore), then you will almost certainly want to respect the browser’s native back/forward buttons and allow deep-linking to specific locations in your virtual navigation system.

There are many JavaScript libraries for working with browser history and the HTML5 pushState feature. Currently my favourite is history.js (license: New BSD) by Benjamin Lupton, because of its robustness, great pushState support, support for older browsers, and because it has no dependencies.

panes.js integrates with history.js, so once you’ve added a reference to history.js, you can start using UrlLinkedPaneHistory instead of PaneHistory. Specify the name of one or more URL parameters that the pane will use to represent what data it is showing. In this case, I’ll call my parameter “location”:

var paneHistory = new UrlLinkedPaneHistory({
    params: { location: 'continents' }

Then, update your paneHistory.navigate call so that it specifies which URL parameter is to be updated (in this case, my only parameter, “location”):

$("a").click(function (evt) {
    var dest = (evt.srcElement ||"#")[1];
    paneHistory.navigate({ location: dest });
    return false;

And finally, since it no longer makes sense for “back” clicks to affect only a single pane (the URL history is global), update your “back” button handler so that it performs a global browser “back” navigation:

$(".goBack").click(function () {

… and you’re done. Now if you run the follow demo full-screen (click the link below the fake phone UI), you’ll see the URL update as you navigate around, and you can use the back/forward buttons (still getting the animated transitions), and can bookmark or refresh the page without losing your position. If your browser supports HTML5 pushState, for example recent versions of Chrome and Firefox, then your URLs will be updated with real querystring parameters as you go. If your browser doesn’t support pushState, history.js will gracefully degrade to using a URL hash.

Try it:

Note: If you want to be able to see the URL updating,
and to use the back/forward buttons, view this example full screen

Dynamically generating panes

If you do a view HTML source on either of the two previous demos, you’ll see that there’s a long list of pre-prepared <DIV> elements – one for each pane that you might visit (Europe, Canada, Vancouver, Toronto, etc….). That’s OK if your app only has a small and finite set of visitable panes (e.g., because those panes represent a fixed number of tabs), but it’s awkward if there are a lot of panes, and useless if the number is effectively infinite because panes represent navigation through data in some large external database.

Fortunately, this is easy to fix. Because panes.js doesn’t modify your DOM structure in any way, and requires no initialisation step to start using newly-inserted DOM elements, it composes perfectly with any external mechanism for updating the DOM. In this example, I’m going to use Knockout.js to inject new panes dynamically as data is fetched from some external source.

The trick here is to make the UrlLinkedPaneHistory a property of your Knockout view model. For example:

function AppViewModel() {
    this.paneHistory = new UrlLinkedPaneHistory({
        params: { location: null },
        // Making the set of history entries observable, so we can dynamically generate corresponding DIVs
        entries: ko.observableArray([]),
        // Each time the visitor navigates forwards, this will be called to fetch data for the new pane
        loadPaneData: function (params, callback) {
            // Here I'm loading data from some external source, asynchronously
            locationInfoService.getLocationInfoAsync(params.location, callback);
ko.applyBindings(new AppViewModel());

(Note: do a “view source” on the live example below if you want to see the finished code and what JS libraries you must reference to make all this work.)

Now the set of history entries is observable, we can ask Knockout to generate corresponding DIVs dynamically, by using a “foreach” binding:

<div class="body row" data-bind="foreach: paneHistory.entries">
    <div id="location-continents" class="pane scroll-y" data-bind="attr: { id: paneId }">
        <h3 data-bind="text:"></h3>

Notice that Knockout will assign an ID property to each pane <DIV> corresponding to the navigation parameters, so it can associate navigation events with the <DIV> you want to slide into view.

Of course, you don’t just want to display the “name” property of each item you’re visiting – you want to generate some more UI for each pane. Let’s generate a list of child locations that the user can navigate to:

<div class="body row" data-bind="foreach: paneHistory.entries"> 
    <div id="location-continents" class="pane scroll-y" data-bind="attr: { id: paneId }"> 
        <h3 data-bind="text:"></h3> 
        <ul data-bind="foreach: paneData.children"> 
            <li data-bind="text: name, 
                            click: $root.navigate, 
                            css: { navigable: childLocations.length }"></li> 

Each of the <li> elements there will try to invoke a viewmodel method called “navigate” when you click it. Implement that by adding a “navigate” method to your viewmodel:

function AppViewModel() {
    // Rest of class unchanged
    this.navigate = function (evt) {
        var destination = ko.dataFor(evt.srcElement ||;
        if (destination.childLocations.length)
            this.paneHistory.navigate({ location: });
    } .bind(this);

Now the visitor will be able to navigate forwards through the hierarchy of locations. What about navigating backwards too? You can put a “back” button into the header pane, and use a Knockout binding to make its text update to show the name of parent location (e.g., “< Europe”):

<div class="header row">
    <p data-bind="with: paneHistory.currentData().parent">
        <button data-bind="click: $root.navigate">&lt; <span data-bind="text: name"></span></button>

Done. Your visitor can now navigate through an arbitrarily deep hierarchy, with the data being pulled from the server as needed and dynamically rendered on the client. The browser’s back/forward buttons still work, deep linking works, and there are smooth animated transitions. And you wrote about 15 lines of JavaScript Smile. Have a go with it:

Note: If you want to be able to see the URL updating,
and to use the back/forward buttons, view this example full screen

What’s next?

Well, what are you interested in? Possible next posts in this series:

  • Using all this stuff to build a complete application with meaningful functionality
  • Making this kind of Single Page Application (SPA) work offline via HTML5 offline support
  • Packaging and selling such apps on mobile appstores via PhoneGap/Callback
  • Data access: editing collections of entities, and letting the user track, synchronise, and revert their changes

If you’re building single page applications, whether for mobile or desktop or both, please let me know what sort of technologies you’re using, what challenges you face, and what kinds of features you’d like to see baked into the ASP.NET/MVC stack.

21 Responses to Full-height app layouts: Navigation and History

  1. Stephen Patten


    Personally I’d be interested in item 1 and 4 as your layout is going to be used in my current LOB MVC3 application.

    Thank you,

  2. Dirk

    Loved these last 3 posts! They really helped me make the current web app for my office look and feel much nicer. Especially history and back buttons have always confounded me. We’re currently developing our apps with ASP.Net/MVC3 and I’m pushing the use of Knockout as hard as I can :)

    From my point of view it would be most interesting to see your take on the Data Access part.

    Anyway, thanks for these!

  3. Joel

    I am using MVC3, L2E, Ninject, code first, and knockout.js. Would like to know your thoughts on the best way to build cross-platform native mobile/tablet apps. Also, I would appreciate anything you can share on web services.

  4. Just wanted to say I like these posts about html/css. Keep it up sir.

  5. If knockout were not an option, would this kind of SPA work with ASP.NET partial views (with links and forms on them)?

  6. Jamey

    1 and 4 please…

  7. Adrián

    I am starting an application and I need help to link the validation of client and server that are part ASP MVC 3 with MVVM knockout.

    1 and 4 plese

  8. Jay

    This is very useful. I see the image of an e-commerce app unde the goal section. Where can I see it live? Thanks for your effort.

  9. Mark

    Vote for Single Page Application demonstration. It is very important to show complete cycle of how to make MVVM style applications with knockout. You can see a lot of MVC frameworks taking on a lot of popularity just because they teach about complete app development.

  10. Bruno

    Great post, thanks!

    One question: why did you use history.js instead of jQuery Address?

    Also, in my work in similar single page apps with multiple panes, one issue was to keep 2 or more panes in sync while maintaining history and back button support.

    I mean, for example, loading a list of items in the main pane while loading a form in the side pane to filter that same list.

    One solution I came with was to add custom attributes like data-left-pane-url = ‘someurl”, data-right-pane-url = ‘someurl” to the body of the page being loaded in the main pane, but maybe there is a more elegant way?

  11. Colin

    Definitely #4, haven’t seen any good examples of using knockoutJS with EF.

    I want to send an object graph (parent-child)to the client, edit with KS (add,edit & delete parent & child records), then reconcile the changes on the server.

  12. philly

    I like your thoughts! Now you could show for example, how to efficiently handle the server side, thinking about server- vs clientside templates, synchronizing the models, maybe even declaring the view models on the server. Also, what about handling differences between different platforms (iphone, wp7..), one has a hardware back button, the other does not, all have different style.
    Keep up the nice and clean work! =)

  13. Anthony

    What I would like to be able to accomplish is the following. Do you think you could help me with an example?

    * Each left hand body list item (think the previous article) I would like load dynamically.

    * Clicking on dynamically loaded list time would open a corresponding pane in the right hand body.

    * All right hand body frames are independent with respect to history, state. (maybe this is why you have the this.urlLinkOptions.idPrefix?) I guess we will need another level of indirection for the AppViewModel’s paneHistory and navigate functions.

    Thanks in advanced for any help suggestions you may have. Feel free to send me email if you would like.



  14. Anthony

    Incase anyone else wants to use knockout.2.0.0 with the examples take a look at this groups post for a workaround to the error you will receive.

  15. Joe

    Great stuff Steven! One question: if i use this layout on the iphone/ipod, the address bar stays in place, and I can’t use the
    setTimeout(function() { window.scrollTo(0, 1) }, 100);
    trick to disappear it.
    Is it possible to use this technique and still hide the url bar on the iphone/ipod?

  16. Great series of posts!

    If u plan to make another post about the WebApp development I would appreciate it. I haven´t a favourite topic, think all are very interesting. What about all, step by step ;-)

  17. Very interested in items 1 and 4.

  18. David B. Bitton

    How can I apply these concepts to the Twitter Bootstrap framework? Thanks!

  19. Gregory

    1 and 4 please

  20. Peter

    Just downloaded the Delivery Tracker app from github. Build bombs:
    System.Reflection.TargetInvocationException was unhandled by user code
    Message=Exception has been thrown by the target of an invocation.
    at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)

    I would like to see it work…

  21. Plurby

    Always wanted to say: Great post.
    It helped me to start in a lot of my projects and for that i’ll post an interesting bug that i’ve experienced today.
    If user has a IE group policy defined “localhost is running in Compatibility View because ‘Display all websites in Compatibility View’ is checked.” panes won’t work well. To bypass this limitation add a meta tag (it must be first) in your view: