If you want to generalize your code to do the same thing both when you are visiting #section1
through an external link, and internally throught <a href="#section1">Section 1</a>
, you can listen to the hashchange
event. It won't update while scrolling though, but if you generalize the code and make it reusable, I'm sure it's easy to combine the techniques.
Try Ben Alman's jQuery hashchange event plugin and add a callback calling the same function. You might want to use it together with jQuery urlInternal: Easily test URL internal-, external-, or fragment-ness and perhaps jQuery BBQ: Back Button & Query Library, also by Ben Alman.
Here's some code, quickly adapted from a project where I use it in the same way to activate different tabs in a tab row. (I use all three plugins mentioned above, but I don't remember if all of them were necessary for this snippet.)
(function() {
var menuLinksSelector = "#menu-main-menu a",
menuLinkHighlightClass = "current";
$.fn.extend({
filterLinksToFragment: function(fragment) {
var $this = $(this),
$filtered = $this.filter("a:urlFragment").filter(function() {
var $this = $(this),
thisFragment = $.param.fragment($this.attr('href'));
return (thisFragment === fragment);
});
return $filtered;
}
});
function highlightMenuItem(fragment) {
var $menuLinks = $(menuLinksSelector),
$selectedMenuLink = $menuLinks.filterLinksToFragment(fragment);
$menuLinks.removeClass(menuLinkHighlightClass);
$menuItem.addClass(menuLinkHighlightClass);
}
function highlightCurrentMenuItem() {
var currentFragment = $.param.fragment();
if (currentFragment !== undefined && currentFragment !== "") {
highlightMenuItem(currentFragment);
}
}
$window.on('hashchange', function() {
// Activate the current URL's #part-anything link
highlightCurrentMenuItem();
});
// Trigger the event (useful on page load).
$window.hashchange();
}());
if you use this code, you won't need to use the .click(...)
handler you have in your question, except perhaps to cancel the click event, since you have plugins for scrolling.