Patrick
Patrick

Reputation: 308

jQuery - Adding active class to submenus in a menu

I have a sidebar menu which I am using for navigation throughout my website and I am wanting to be able to dynamically add the active class to the appropriate menu item. I've tried using the code bellow but It doesnt seem to be doing anything.

    var page = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
    $('ul li a[href="'+ page +'"]').parent().addClass('active');
    $('ul li a').filter(function() {
        return this.href == page;
    }).parent().addClass('active');

I might have my syntax wrong for the selector so below I have included a snippet of the sidebar.

    <div id="sidebar" class="nav-collapse ">
        <ul class="sidebar-menu" id="nav-accordion">
            <li>
                <a href="dash.php">
                    <i class="fa fa-dashboard"></i>
                    <span>Home</span>
                </a>
            </li>

            <li class="sub-menu">
                <a href="javascript:;" >
                    <i class="fa fa-cogs"></i>
                    <span>Tools</span>
                </a>
                <ul class="sub">
                    <li><a href="index.php">Uptime</a></li>
                </ul>
            </li>
        </ul>
    </div>

Upvotes: 0

Views: 2018

Answers (3)

David Thomas
David Thomas

Reputation: 253308

I'd suggest that the easiest way would be to filter the collection of <a> elements to see which an href property equal to the current page, then add the 'active' class-name to the closest ancestor <li> element:

// caching the URL of the page:
var pageURL = document.location.href;

// selecting all <a> elements within the element with the
// id of 'nav-accordion'; then using the filter() method
// to filter the collection returned by the selector:
$('#nav-accordion a').filter(function (index, anchorEl) {

    // only those elements for which this assessment returns
    // Boolean true will be retained.
    // here we test that the 'href' property (not the attribute),
    // which is an absolute URL, is equal the current page's URL:
    return anchorEl.href === pageURL;

// for those elements remaining in the collection we navigate to
// each retained element's closest ancestor '<li>' element and
// and then add the 'active' class-name to that <li>:
}).closest('li').addClass('active');

References:

Upvotes: 1

Micaela
Micaela

Reputation: 132

Try this

$( "#sidebar" ).on('click', function() {
$(this).addClass('active').siblings().removeClass('active');
});

I hope this helps

Upvotes: 0

alaney
alaney

Reputation: 623

window.location does not return a string. If you open your browser's developer tools and inspect it you will see it is an object. Not sure what value you're after, but I think you would start with the pathname property e.g., var path = window.location.pathname; then do some regex to get the page name if necessary.

Upvotes: 0

Related Questions