YUI 3.x Home -

YUI Library Examples: Browser History Utility: Simple Navigation Bar

Browser History Utility: Simple Navigation Bar

This example demonstrates how to use the Browser History Utility to "ajaxify" a simple navigation bar.

Basic markup

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>YUI Browser History Utility - Simple Navigation Bar Example</title>
  5. </head>
  6. <body>
  7. <div id="doc">
  8. <div id="hd">
  9. <h3>Navigation Links</h3>
  10. <div id="nav">
  11. <ul>
  12. <li><a href="?section=home">Home</a></li>
  13. <li><a href="?section=overview">Overview</a></li>
  14. <li><a href="?section=products">Products</a></li>
  15. <li><a href="?section=contactus">Contact Us</a></li>
  16. </ul>
  17. </div>
  18. </div>
  19. <div id="bd">
  20.  
  21. <?
  22. $section = "home";
  23. $sections = array("home", "overview", "products", "contactus");
  24. if (isset($_GET["section"]) && in_array($_GET["section"], $sections)) {
  25. $section = $_GET["section"];
  26. }
  27.  
  28. include($section . ".php");
  29. ?>
  30. </div>
  31. <div id="ft">YUI Browser History Utility - Simple Navigation Bar Example</div>
  32. </div>
  33. </body>
  34. </html>
&lt;!doctype html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;YUI Browser History Utility - Simple Navigation Bar Example&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id="doc"&gt;
      &lt;div id="hd"&gt;
        &lt;h3&gt;Navigation Links&lt;/h3&gt;
        &lt;div id="nav"&gt;
          &lt;ul&gt;
            &lt;li&gt;&lt;a href="?section=home"&gt;Home&lt;/a&gt;&lt;/li&gt;
            &lt;li&gt;&lt;a href="?section=overview"&gt;Overview&lt;/a&gt;&lt;/li&gt;
            &lt;li&gt;&lt;a href="?section=products"&gt;Products&lt;/a&gt;&lt;/li&gt;
            &lt;li&gt;&lt;a href="?section=contactus"&gt;Contact Us&lt;/a&gt;&lt;/li&gt;
          &lt;/ul&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div id="bd"&gt;
 
&lt;?
$section = "home";
$sections = array("home", "overview", "products", "contactus");
if (isset($_GET["section"]) && in_array($_GET["section"], $sections)) {
   $section = $_GET["section"];
}
 
include($section . ".php");
?&gt;
      </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

  1. &lt;iframe id="yui-history-iframe" src="assets/blank.html"&gt;&lt;/iframe&gt;
  2. &lt;input id="yui-history-field" type="hidden"&gt;
&lt;iframe id="yui-history-iframe" src="assets/blank.html"&gt;&lt;/iframe&gt;
&lt;input id="yui-history-field" type="hidden"&gt;

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:

  1. 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:

  1. function loadSection(section) {
  2.  
  3. var url = section + '.php',
  4. cfg = {
  5. on: {
  6. success: function (id, o, args) {
  7. Y.get('#bd').set('innerHTML', o.responseText);
  8. },
  9.  
  10. failure: function (id, o, args) {
  11. // Fallback...
  12. }
  13. }
  14. };
  15.  
  16. Y.io(url, cfg);
  17. }
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":

  1. bookmarkedSection = Y.History.getBookmarkedState('navbar');
  2. querySection = Y.History.getQueryStringParameter('section');
  3. 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:

  1. 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:

  1. function initializeNavigationBar() {
  2. Y.on('click', function (evt) {
  3. var el = evt.target;
  4. while (el.get('id') !== 'nav') {
  5. if (el.get('nodeName').toUpperCase() === 'A') {
  6. evt.preventDefault();
  7. section = Y.History.getQueryStringParameter('section', el.get('href')) || 'home';
  8. if (!Y.History.navigate('navbar', section)) {
  9. // Fallback...
  10. loadSection(section);
  11. }
  12. break;
  13. } else {
  14. el = el.get('parentNode');
  15. }
  16. }
  17. }, '#nav');
  18.  
  19. currentSection = Y.History.getCurrentState('navbar');
  20. loadSection(currentSection);
  21. }
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

  1. Y.History.subscribe('history:ready', initializeNavigationBar);
  2. Y.History.initialize('#yui-history-field', '#yui-history-iframe');
Y.History.subscribe('history:ready', initializeNavigationBar);
Y.History.initialize('#yui-history-field', '#yui-history-iframe');

Copyright © 2009 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings