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();
}
};6 comments
I haven't ever used jquery before, and I am trying to figure out how to use your plugin. I am kind of at a loss without pin pointed instructions of, "Place this function here, make sure you link to this script file there". The example you have stays within one page, but I think it should work when linking between two different pages.
Would you be able to flesh out your instructions for the most simple of users like myself? I am supposed to link to your plugin file and the jquery library in the source file with the list of links. I also link to the library and your plugin on the end html page?
Jeff
How to move all the anchor tags to the top of the page?
I don't want to jump to respective anchor.
You know?