views:

148

answers:

1

I'm using the same js as the one answered in this question: http://stackoverflow.com/questions/302955/active....

my problem is, instead of adding the class to a default link i would like to add the class to a link with the same directory.

example: Page2 is in a different directory. a link, outside of the nav, is clicked on that page. when you go to the next page, how can I keep that active class on the Page2 link?

Here's the nav

    <div id="nav">
              <ul>
                <li><a href="index.html">Home</a></li>
                <li><a href="test/index.html">Page2</a></li>
                <li><a href="test2/index.html">Page3</a></li>
</ul>
</div>

Below is my jquery. the first part works perfect the second part is where i'm having trouble:

function markActiveLink() {var currentURL = window.location.toString().split("/");
$("#nav li a").filter(function() {
//alert(currentURL);
    return $(this).attr("href") == currentURL[currentURL.length-1];
    }).parent().addClass("current");
if($("#nav li").hasClass("current") == false) {
     alert(currentURL[currentURL.length-2]);

    }
 }

markActiveLink();

Thank you in advance!

A: 

This should work. Takes into account whole path not only last part of it.

function markActiveLink() {
    var path = location.pathname.substring(1);
    $('#nav li a[href="' + path + '"]').parent().addClass("current");
    if($("#nav li").hasClass("current") == false) {
      //whatever e.g. select default
      $('#nav li').eq(0).addClass("current");
    }
}

markActiveLink();
jitter
Hi jitter,that didn't work. it just kept the class on the first element.
cadenage
are you sure? I removed a `$` from the first selector shortly after posting. Can build in an `alert(path)` and post in a comment a few values for it
jitter
So? Any progress on this? Can you provide sample values to what path evaluates?
jitter