Anchor-based URL navigation, Take 2

Posted

Update: I encourage everyone who arrives at this post to check out Ben Alman's jQuery BBQ plugin -- it provides a ton of functionality above and beyond what this plugin offers, is much more robust, and is built to take advantage of the latest version of jQuery. While you're welcome to use the plugin on this page, it is no longer supported. I noticed I was getting a lot of visits via Google for my post on anchor-based URL navigation with jQuery, so I decided to write a plugin that would accomplish the same thing.

Call this function on an element that contains "panels" which, in turn, contain anchors. The container element should contain ONLY related panels, as this plugin will show only one first-child element of the container at once. This plugin will look at the current URL and see whether it contains an anchor. For example:
http://www.mysite.com/index.html#panel1
If it finds an anchor, it will look for the panel that contains the associated anchor tag; it will show this panel using the function defined by the showFn option, and it will hide the panel's siblings using the function defined by the hideFn option. If the nav option is set, it will use the nav option setting as a selector to locate the page's navigation. It will look for a link with an href matching the anchor; if it finds a matching link, it will run the function defined by the currentNavFn option on the link element (useful for setting the current nav item). If the nav option is set, it will also set up onclick functions on each of the links in the nav that refer to anchors on the page; the onclick function will use the show and hide options to show and hide the associated panels.

Options

  • showFn function to show the current panel
  • hideFn function to hide the current panel's siblings
  • nav selector for the page's navigation section
  • currentNavFn function to run on the link in the nav that is associated with the anchor
  • anchorClass class assigned to anchor tags; setting this will improve the speed on pages with lots of links
  • noAnchorFn function to run if the URL does not contain an anchor
Default option values:
var options = {
  showFn: function() { $(this).show(); },
  hideFn: function() { $(this).hide(); },
  nav: null,
  currentNavFn:
    function() {
      // this will add a class to the parent of the
      // link that matches the currently selected anchor
      $(this).parent().siblings().removeClass('anchor-nav-current');
      $(this).parent().addClass('anchor-nav-current');
    },
  anchorClass: null,
  noAnchorFn:
    function() {
      // this will show the first panel
      // if the URL doesn't contain an anchor
      $container.children().hide().eq(0).show();
    }
};

Filed under  //  anchor   jquery   navigation   plugins   progressive enhancement  
Comments (6)
Posted