Anchor-based URL navigation, Take 2
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
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
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();
}
};