NotAnotherCliche
NotAnotherCliche

Reputation: 383

Active class for active URLs menu (not using LI's)

I have this HTML code and I want to add a class of "active" to the div contained within the link that is active. (I've intentionally created this navigation WITHOUT using an unordered list.)

<nav role="navigation" id="navigation">
<a href="rings-c-24.html" title="Rings"><div class="primary-navigation">Rings</div></a>
<a href="earrings-c-23.html" title="Earrings"><div class="primary-navigation">Earrings</div></a>
<a href="necklaces-c-26.html" title="Necklaces"><div class="primary-navigation">Necklaces</div></a>
<a href="bracelets-and-bangles-c-22.html" title="Bracelets & Bangles"><div class="primary-navigation">Bracelets & Bangles</div></a>
</nav><!-- end of navigation-->

I've tried something like this, but I am certain I'm not referencing my parents and children correctly. Please help, thank you!

$(function(){
    var current = location.pathname;
    $('.primary-navigation').each(function(){
        var $this = $(this).parent();
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
}) 

Upvotes: 0

Views: 245

Answers (2)

Sridhar R
Sridhar R

Reputation: 20408

Try this

 $(function() {
    var pgurl = window.location.href.substr(window.location.href
    .lastIndexOf("/")+1);
    $("#navigation a").each(function(){
    if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
    $(this).find(".primary-navigation").addClass("active");
    })
    });

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78525

You can use an attribute selector for this:

$("#navigation a[href='"+location.pathname+"']").find(".primary-navigation").addClass("active");

Or if you wanted to add the class to the <a> tag:

$("#navigation a[href='"+location.pathname+"']").addClass("active");

Upvotes: 1

Related Questions