YUI 3.x Home -

Site Search (YDN & YUIBlog):

# 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.

View example in new window.

### Basic markup

    &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>

    &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>

<!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

    &lt;iframe id="yui-history-iframe" src="assets/blank.html"&gt;&lt;/iframe&gt;&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;

<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', 'querystring', 'history');

    YUI().use('io', 'querystring', 'history');

YUI().use('io', 'querystring', '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.one('#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.one('#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.one('#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 `QueryString.parse` 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.QueryString.parse(el.get('href').split('?')[1]).section;initSection = bookmarkedSection || querySection || 'home';

    bookmarkedSection = Y.History.getBookmarkedState('navbar');
    querySection = Y.QueryString.parse(el.get('href').split('?')[1]).section;
    initSection = bookmarkedSection || querySection || 'home';

bookmarkedSection = Y.History.getBookmarkedState('navbar'); querySection = Y.QueryString.parse(el.get('href').split('?')[1]).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).on('history:moduleStateChange', loadSection);

    Y.History.register('navbar', initSection).on('history:moduleStateChange', loadSection);

Y.History.register('navbar', initSection).on('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, action, section;        while (el.get('id') !== 'nav') {            if (el.get('nodeName').toUpperCase() === 'A') {                evt.preventDefault();                action = Y.QueryString.parse(el.get('href').split('?')[1]);                section =  action.section || '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, action, section;
            while (el.get('id') !== 'nav') {
                if (el.get('nodeName').toUpperCase() === 'A') {
                    evt.preventDefault();
                    action = Y.QueryString.parse(el.get('href').split('?')[1]);
                    section =  action.section || '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, action, section; while (el.get('id') !== 'nav') { if (el.get('nodeName').toUpperCase() === 'A') { evt.preventDefault(); action = Y.QueryString.parse(el.get('href').split('?')[1]); section = action.section || '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.on('history:ready', initializeNavigationBar);Y.History.initialize('#yui-history-field', '#yui-history-iframe');

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

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

Copyright © 2010 Yahoo! Inc. All rights reserved.

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