This example demonstrates how to use the Browser History Manager to "ajaxify" a simple navigation bar.
1 | <html> |
2 | <head> |
3 | <title>YUI Browser History Manager - Simple Navigation Bar Example</title> |
4 | </head> |
5 | <body> |
6 | <div id="doc"> |
7 | <div id="hd"> |
8 | <h3>Navigation Links</h3> |
9 | <div id="nav"> |
10 | <ul> |
11 | <li><a href="?section=home">Home</a></li> |
12 | <li><a href="?section=overview">Overview</a></li> |
13 | <li><a href="?section=products">Products</a></li> |
14 | <li><a href="?section=contactus">Contact Us</a></li> |
15 | </ul> |
16 | </div> |
17 | </div> |
18 | <div id="bd"> |
19 | <?php |
20 | |
21 | $section = "home"; |
22 | $sections = array("home", "overview", "products", "contactus"); |
23 | if (isset($_GET["section"]) && in_array($_GET["section"], $sections)) { |
24 | $section = $_GET["section"]; |
25 | } |
26 | |
27 | include( $section . ".php" ); |
28 | |
29 | ?> |
30 | </div> |
31 | <div id="ft">YUI Browser History Manager - Simple Navigation Bar Example</div> |
32 | </div> |
33 | </body> |
34 | </html> |
view plain | print | ? |
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 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 Connection Manager 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 Manager will help us work around this issue.
1 | <iframe id="yui-history-iframe" src="assets/blank.html"></iframe> |
2 | <input id="yui-history-field" type="hidden"> |
view plain | print | ? |
This markup should be inserted right after the opening body
tag.
In our example, we need the Connection Manager, Event Utility, DOM Utility, and the Browser History Manager:
1 | <script src="yahoo-dom-event.js"></script> |
2 | <script src="connection.js"></script> |
3 | <script src="history.js"></script> |
view plain | print | ? |
Use the YUI Connection Manager's asyncRequest
to achieve this:
1 | function loadSection(section) { |
2 | var url = section + ".php"; |
3 | |
4 | function successHandler(obj) { |
5 | // Use the response... |
6 | YAHOO.util.Dom.get("bd").innerHTML = obj.responseText; |
7 | } |
8 | |
9 | function failureHandler(obj) { |
10 | // Fallback... |
11 | location.href = "?section=" + section; |
12 | } |
13 | |
14 | YAHOO.util.Connect.asyncRequest("GET", url, |
15 | { |
16 | success:successHandler, |
17 | failure:failureHandler |
18 | } |
19 | ); |
20 | } |
view plain | print | ? |
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.)
Use the YAHOO.util.History.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 YAHOO.util.History.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 | var bookmarkedSection = YAHOO.util.History.getBookmarkedState("navbar"); |
2 | var querySection = YAHOO.util.History.getQueryStringParameter("section"); |
3 | var initialSection = bookmarkedSection || querySection || "home"; |
view plain | print | ? |
Use the YAHOO.util.History.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 | YAHOO.util.History.register("navbar", initialSection, function (state) { |
2 | // Load the appropriate section: |
3 | loadSection(state); |
4 | }); |
view plain | print | ? |
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 | // Process links |
3 | var anchors, i, len, anchor, href, section, currentSection; |
4 | anchors = YAHOO.util.Dom.get("nav").getElementsByTagName("a"); |
5 | for (i = 0, len = anchors.length; i < len; i++) { |
6 | anchor = anchors[i]; |
7 | YAHOO.util.Event.addListener(anchor, "click", function (evt) { |
8 | href = this.getAttribute("href"); |
9 | section = YAHOO.util.History.getQueryStringParameter("section", href) || "home"; |
10 | // If the Browser History Manager was not successfuly initialized, |
11 | // the following call to YAHOO.util.History.navigate will throw an |
12 | // exception. We need to catch it and update the UI. The only |
13 | // problem is that this new state will not be added to the browser |
14 | // history. |
15 | // |
16 | // Another solution is to make sure this is an A-grade browser. |
17 | // In that case, under normal circumstances, no exception should |
18 | // be thrown here. |
19 | try { |
20 | YAHOO.util.History.navigate("navbar", section); |
21 | } catch (e) { |
22 | loadSection(section); |
23 | } |
24 | YAHOO.util.Event.preventDefault(evt); |
25 | }); |
26 | } |
27 | |
28 | // This is the tricky part... The window's onload handler is called when the |
29 | // user comes back to your page using the back button. In this case, the |
30 | // actual section that needs to be loaded corresponds to the last section |
31 | // visited before leaving the page, and not the initial section. This can |
32 | // be retrieved using getCurrentState: |
33 | currentSection = YAHOO.util.History.getCurrentState("navbar"); |
34 | loadSection(currentSection); |
35 | } |
view plain | print | ? |
onReady
method
Use the Browser History Manager onReady
method to initialize the application.
1 | YAHOO.util.History.onReady(function () { |
2 | initializeNavigationBar(); |
3 | }); |
view plain | print | ? |
Simply call YAHOO.util.History.initialize
, passing in the id of the input field and IFrame we inserted
in our static markup:
1 | // Initialize the browser history management library. |
2 | try { |
3 | YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe"); |
4 | } catch (e) { |
5 | // The only exception that gets thrown here is when the browser is |
6 | // not supported (Opera, or not A-grade) Degrade gracefully. |
7 | // Note that we have two options here to degrade gracefully: |
8 | // 1) Call initializeNavigationBar. The page will use Ajax/DHTML, |
9 | // but the back/forward buttons will not work. |
10 | // 2) Initialize our module. The page will not use Ajax/DHTML, |
11 | // but the back/forward buttons will work. This is what we |
12 | // chose to do here: |
13 | loadSection(initSection); |
14 | } |
view plain | print | ? |
You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.
Copyright © 2009 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Copyright Policy - Job Openings