tags:

views:

57

answers:

3

I need to apply a class ".selected" to a navigation item when the user is on the corresponding page, so that when the user clicks on "Products", it goes to the products page but the Products nav item remains selected. How can I accomplish this using jQuery? I suppose I would need to get the URL of the page an apply the style to the corresponding nav item, correct?

+1  A: 

assuming the element you want styled .selected has an id same as the html file currently in the browser:

$(document).ready(function() {
  ...
  var page = window.location.href.match(/\/(\w+).htm/)[1];
  $('#' + page).addClass('selected');
  ...
Scott Evernden
+1  A: 

I assume that you'll be doing some sort of AJAX system where you won't be reloading the menu on every click, otherwise this should definitely be done server side. If not, you can use the following

HTML

<ul id='main'>
    <li>menu</li>
    <li>menu</li>
    <li>menu</li>
</ul>​​​

Javascript:

$('ul#main > li').click(function() {
        $('ul#main > li.selected').removeClass('selected');
        this.setAttribute('class','selected');
}​​​​​​​​​);​

Here's a link to try it out: http://jsfiddle.net/6zpJX/

Robert
would be easy to just, `$('ul#main > li').click(function() { $(this).addClass('selected').siblings().removeClass('selected'); }​​​​​​​​​);​` ^^,
Reigel
+1  A: 

Here is a simple example, if you wish to match the entire URL ('http://example.com/mydir/mypage.html'):

  $(function() {
    var url = window.location;
    $('a[href="' + url + '"]').addClass('selected');
  });

Or, to match the path ('/mydir/mypage.html'):

  $(function() {
    var url = window.location.path;
    $('a[href="' + url + '"]').addClass('selected');
  });
Matt Austin