Tuesday, June 21, 2011

Anatomy of an HTML5 Page Transition

One of the sexy new trends in HTML5 development right now is Page Transitions.  One of the first places I noticed Page Transitions in use was the GitHub Repository Explorer; as you click around to different directories and files, the content slides in and out without reloading the page.

While most of this functionality can be achieved through Javascript alone, the actual URL History manipulation has only been available in the (relatively) recent incarnations of HTML5.  When you add in the ability to take advantage of CSS3 transitions for sliding pages in and out, you end up with a pretty modern example of HTML5 capabilities.


Here is a pretty typical scenario; two pages with identical layout, but different content.


  1. User clicks a link that has the transition-link attribute
  2. Download the page with $.ajax call and grab content (<div> with role="main" attribute)
  3. Slide out the old content, slide in our new content.
  4. Change the menu button highlight and URL.
Page HTML Structure

Setting up your pages to use transitions requires some plumbing hookup to specify what parts of the page are content and what links should load new content in.  In our case, we attach handlers for any link elements with a transition-link attribute, and we look for a div element with a role="main" attribute as our content area.

Retrieving The Other Page With jQuery

When our page loads, we attach to all our transition links click events so we can load our other page with ajax instead of with a browser refresh.

You may notice that we are taking advantage of jQuery's new $.Deferred object for the loadPage function.  This lets us specify callbacks for when the page is done loading, or if there is an error loading the other page.

Transitioning The Page Contents Out and In

Once we've loaded the new page's contents, we're ready to start transitioning the old content out and slide the new content in.  To do this, I took advantage of the jQuery UI Effects library and chained some call backs to insert the new content after we finish hiding the current content.

Bonus Points: We get some bonus points here at the bottom for detecting CSS Transitions and using those instead.  The style for the CSS3 Transitions can be found in the jQuery Mobile source on GitHub.

A more styled fleshed out version of this concept can be found live on my DropBox account.