views:

90

answers:

2

using javascript, what options are there to set the currently selected navigation item?

Assuming the page refreshes on whenever someone clicks on a navigation link, the only way would be to either do it on the server side or set it dynamically by looking up the current URL?

Are there any other tricks?

+1  A: 

The window.location.pathname property is reliable, and if you were to use a substring comparison with the href of links in the menu it would be quick (ie no regex testing).

var menuLinks = document.getElementById('menu').getElementsByTagName('a');

for (var i = 0; i < menuLinks.length; i++) {
  if (menuLinks[i].href.indexOf(window.location.pathname) > -1) {
    doSomething();
  }
}
tj111
+1  A: 

I set a class attribute on the <body> element for my pages, like 'home-section' or 'products-section'.

When the page loads, you can use JavaScript to retrieve the value of the attribute and set the navigation class appropriately.

if ($("body").attr("class") == 'home-section') {
    $("li#primary-nav-home").addClass("active");
}

You could also accomplish the same thing with straight CSS with the appropriate selector and get rid of the need for classes.

body.home-section li#primary-nav-home { /* styling rules */ }

Mark Hurd