0

I have the HTML code as given below to add the navigation to my site. (Note that the list is nested)

<div id="navigation">
       <ul>
        <li><a href="default.html">Home</a></li>
        <li><a href="about.html">About us</a></li>
        <li><a href="help.html">Help</a></li>
        <li><a href="#">DropDown</a>
          <ul>
            <li><a href="#">Link 1</a></li>
            <li><a href="#">Link 2</a></li>
            <li><a href="#">Link 3</a></li>
          </ul>
        </li>
        <li class="last"><a href="#">A Last Link Text</a></li>
      </ul>
</div>

I want to show the currently active page link in new color. So the corresponding list item should have the class active and I use the CSS to change the color. For example, if the default.html is the currently opened page, the code should be <li class=“active”><a href="default.html">Home</a></li>.

How to do that in jQuery and JavaScript (I need both for two different websites). Can anyone help me?

Thanks for your help.

user2435840
  • 143
  • 1
  • 1
  • 5
  • 1
    Please post your JavaScript code in the question so we can help. – elclanrs Sep 27 '13 at 04:30
  • Actually, I don't know javascript and jquery. But, I came to know that we can select an element and add class using the both scripts.That is why I am asking. – user2435840 Sep 27 '13 at 04:34
  • Then you need to do bit of research first. We expect code in questions that ask for code. This is a good place to start http://jqueryfundamentals.com. Then check here on how to ask good questions http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist – elclanrs Sep 27 '13 at 04:36

2 Answers2

0

Get your URL / Parse it:

var pathname = window.location.pathname;

Then add the class:

Jquery:

$(element).addClass('classname');

JS: How do I add a class to a given element?

Community
  • 1
  • 1
STLMikey
  • 1,210
  • 7
  • 19
0

Try this

$(document).ready(function () {
    var url = location.href;
    $('#navigation li a').each(function () {
        var thisHref = this.getAttribute('href');
        if (thisHref !== '#' && url.indexOf(thisHref) !== -1) {
            $(this.parentNode).addClass('active');
            return;
        }
    });
});
Joe Simmons
  • 1,828
  • 2
  • 12
  • 9