Guillemo
Guillemo

Reputation: 1

Apply a class based on the page

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?

Upvotes: 0

Views: 172

Answers (3)

Scott Evernden
Scott Evernden

Reputation: 39926

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');
  ...

Upvotes: 1

Robert
Robert

Reputation: 21388

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/

Upvotes: 1

Matt Austin
Matt Austin

Reputation: 2622

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');
  });

Upvotes: 1

Related Questions