Browser History Utility: Simple Navigation Bar
This example demonstrates how to use the Browser History Utility to "ajaxify" a simple navigation bar.
Basic markup
<!doctype html> <html> <head> <title>YUI Browser History Utility - Simple Navigation Bar Example</title> </head> <body> <div id="doc"> <div id="hd"> <h3>Navigation Links</h3> <div id="nav"> <ul> <li><a href="?section=home">Home</a></li> <li><a href="?section=overview">Overview</a></li> <li><a href="?section=products">Products</a></li> <li><a href="?section=contactus">Contact Us</a></li> </ul> </div> </div> <div id="bd"> <? $section = "home"; $sections = array("home", "overview", "products", "contactus"); if (isset($_GET["section"]) && in_array($_GET["section"], $sections)) { $section = $_GET["section"]; } include($section . ".php"); ?> </div> <div id="ft">YUI Browser History Utility - Simple Navigation Bar Example</div> </div> </body> </html>
<!doctype html> <html> <head> <title>YUI Browser History Utility - Simple Navigation Bar Example</title> </head> <body> <div id="doc"> <div id="hd"> <h3>Navigation Links</h3> <div id="nav"> <ul> <li><a href="?section=home">Home</a></li> <li><a href="?section=overview">Overview</a></li> <li><a href="?section=products">Products</a></li> <li><a href="?section=contactus">Contact Us</a></li> </ul> </div> </div> <div id="bd"> <? $section = "home"; $sections = array("home", "overview", "products", "contactus"); if (isset($_GET["section"]) && in_array($_GET["section"], $sections)) { $section = $_GET["section"]; } include($section . ".php"); ?> </div> <div id="ft">YUI Browser History Utility - Simple Navigation Bar Example</div> </div> </body> </html>
The small portion of PHP code is responsible for including the content specified by the "section" parameter in the URL. This technique avoids having to rewrite common parts of a web site such as the header and footer.
This page is already fully functional. However, clicking on the links in the navigation bar will refresh the entire
page, including portions that are common to all the sections. This is highly inefficient (especially for a large web
site), and using AJAX will allow us to optimize this. The idea is to use client-side scripting to intercept the click
event, cancel it, and use the YUI io
module to asynchronously load the content of the section, which we can
then write to the document using innerHTML. The only downside of this approach is that it breaks the back/forward
buttons, and individual sections cannot be bookmarked anymore. The Browser History Utility will help us work around
this issue.
Add the necessary markup
<iframe id="yui-history-iframe" src="assets/blank.html"></iframe> <input id="yui-history-field" type="hidden">
<iframe id="yui-history-iframe" src="assets/blank.html"></iframe> <input id="yui-history-field" type="hidden">
This markup should be inserted right after the opening <body>
tag.
Set up the YUI Instance
Now, we need to create our YUI instance and tell it to load the io
and history
modules:
YUI().use('io', 'history');
YUI().use('io', 'history');
Write the code necessary to load a section of the web site
Use the YUI io
module to achieve this:
function loadSection(section) { var url = section + '.php', cfg = { on: { success: function (id, o, args) { Y.get('#bd').set('innerHTML', o.responseText); }, failure: function (id, o, args) { // Fallback... } } }; Y.io(url, cfg); }
function loadSection(section) { var url = section + '.php', cfg = { on: { success: function (id, o, args) { Y.get('#bd').set('innerHTML', o.responseText); }, failure: function (id, o, args) { // Fallback... } } }; Y.io(url, cfg); }
Design your application
In our simple example, we have only one module, represented by the navigation bar. We will refer to this module using the identifier "navbar". The state of the navigation module will be represented using the name of the corresponding section ("home", "overview", "products", etc.)
Retrieve the initial state of the navigation module
Use the getBookmarkedState
method to find out the initial state of a module according
to the URL fragment identifier (which is present if the user had previously bookmarked the application).
In our example, we also use the getQueryStringParameter
method to find out the initial state
of a module according to the query string (which is present if the user reached the page using a search engine,
or if the user did not have scripting enabled when previously bookmarking the page). Finally, default to "home":
bookmarkedSection = Y.History.getBookmarkedState('navbar'); querySection = Y.History.getQueryStringParameter('section'); initSection = bookmarkedSection || querySection || 'home';
bookmarkedSection = Y.History.getBookmarkedState('navbar'); querySection = Y.History.getQueryStringParameter('section'); initSection = bookmarkedSection || querySection || 'home';
Register the navigation module
Use the register
method, passing in the navigation module identifier, the initial state
of the navigation module, and the callback function that will be called when the state of the navigation
module has changed:
Y.History.register('navbar', initSection).subscribe('history:moduleStateChange', loadSection);
Y.History.register('navbar', initSection).subscribe('history:moduleStateChange', loadSection);
Write the code that initializes your application
First of all, we want to change the behavior of the links in the navigation bar. In order to do this, we simply
enumerate them, and attach to each individual anchor an onclick
handler. In the onclick
handler, we cancel the event's default behavior and do some custom action.
We also need to display the default section if a section was requested via the URL fragment identifier, and that section is different from the one loaded using PHP:
function initializeNavigationBar() { Y.on('click', function (evt) { var el = evt.target; while (el.get('id') !== 'nav') { if (el.get('nodeName').toUpperCase() === 'A') { evt.preventDefault(); section = Y.History.getQueryStringParameter('section', el.get('href')) || 'home'; if (!Y.History.navigate('navbar', section)) { // Fallback... loadSection(section); } break; } else { el = el.get('parentNode'); } } }, '#nav'); currentSection = Y.History.getCurrentState('navbar'); loadSection(currentSection); }
function initializeNavigationBar() { Y.on('click', function (evt) { var el = evt.target; while (el.get('id') !== 'nav') { if (el.get('nodeName').toUpperCase() === 'A') { evt.preventDefault(); section = Y.History.getQueryStringParameter('section', el.get('href')) || 'home'; if (!Y.History.navigate('navbar', section)) { // Fallback... loadSection(section); } break; } else { el = el.get('parentNode'); } } }, '#nav'); currentSection = Y.History.getCurrentState('navbar'); loadSection(currentSection); }
Initialize the Browser History Utility
Y.History.subscribe('history:ready', initializeNavigationBar); Y.History.initialize('#yui-history-field', '#yui-history-iframe');
Y.History.subscribe('history:ready', initializeNavigationBar); Y.History.initialize('#yui-history-field', '#yui-history-iframe');