BlackrockDigital / startbootstrap

A library of free and open source Bootstrap themes and templates
https://startbootstrap.com
Other
7.19k stars 2.68k forks source link

Automatic adding of "active" class to menu items also matching "parent" URIs #89

Closed alexweissman closed 8 years ago

alexweissman commented 9 years ago

In the sb-admin-2 template, the following code automatically adds the active class to the currently selected menu item by matching the current URI to the URI of the <a> tag:

    var url = window.location;
    var element = $('ul.nav a').filter(function() {
        return this.href == url || url.href.indexOf(this.href) == 0;
    }).addClass('active').parent().parent().addClass('in').parent();
    if (element.is('li')) {
        element.addClass('active');
    }

However, this part: url.href.indexOf(this.href) == 0 also matches any "parent" URIs, highlighting them as well. For example, if I have menu items that link to:

mysite.com/users
mysite.com/users/1

If I click the mysite.com/users/1 menu item, mysite.com/users will also be set to active.

I'm not sure if this is the intended behavior, based on an assumption that the URI naming scheme corresponds to the organization scheme for the menu.

jryd commented 9 years ago

I have experience the same issue with this.

SPikeVanz commented 8 years ago

var url = window.location; var element = $('ul.nav a').filter(function(mysite.com/users mysite.com/users/1) { return this.href == url || url.href.indexOf(this.href) == 0; }).addClass('active').parent().parent().addClass('in').parent(mysite.com/users mysite.com/users/1); if (element.is('li')) { element.addClass('active'); }

alexweissman commented 8 years ago

For what it's worth, here is the modification I made to disable this behavior: https://github.com/alexweissman/UserFrosting/blob/master/public/js/sb-admin-2.js#L29-L37

davidtmiller commented 8 years ago

Thanks @alexweissman for offering this solution. I'll look into this in the next build of SB Admin 2!

ghost commented 8 years ago

Thanks @alexweissman !!!

tellmehowblog commented 4 years ago
var url = window.location;
    var element = $('ul.nav a').filter(function () {
        return this.href == url;
    });

    if (element) {
        element.addClass('active').parents('#side-menu ul').addClass('in');
        element.parents('#side-menu li').addClass('active').parent();
    }
    var element1 = $('.nav.nav-first-level.active a').filter(function () {
        return this;
    });
    if(element1){
        element1.parents(".nav.nav-second-level.collapse").addClass("in");
    }

This solved my issue with Bootstrap 3..