简体   繁体   中英

Showing active menu on a drop down side menu on Bootstrap (AdminLTE)

I want to highlight the active page on the side bar menu. I am using Bootstrap (AdminLTE).

I have tried a number of javascript ways to no avail. Kindly anyone help out. Below is the side bar menu.

<ul class="sidebar-menu" >
  <li class=""><a href="/dashboard"><i class="fa fa-dashboard"></i> <span>Dashboard</span></a> </li>
  <br>
  <li class="treeview">
    <a href=""> <i class="fa fa-cogs"></i> <span> Account Configuarion</span> <i class="fa fa-angle-left pull-right"></i> </a>
    <ul class="treeview-menu">
      <li class="treeview">
        <a href=""> <i class="fa fa-mobile fa-lg"></i> <span>M-PESA C2B</span> <i class="fa fa-angle-left pull-right"></i> </a>
        <ul class="treeview-menu">
          <li class=""><a href="/c2b"><i class="fa fa-arrow-circle-right"></i>C2B Settings</a></li>
          <li class=""><a href="/online-checkout"><i class="fa fa-arrow-circle-right"></i> Online CheckOut</a></li>
          <li class=""><a href="/stk-push"><i class="fa fa-arrow-circle-right"></i> STK Push</a></li>
        </ul>
      </li>
      <li class="treeview">
        <a href=""> <i class="fa fa-mobile fa-lg"></i> <span>M-PESA B2C</span> <i class="fa fa-angle-left pull-right"></i> </a>
        <ul class="treeview-menu">
          <li><a href="b2c-documentation"><i class="fa fa-arrow-circle-right"></i>  B2C Settings</a></li>
        </ul>
      </li>
      <li class="treeview">
        <a href=""> <i class="fa fa-send"></i> <span>SMS</span> <i class="fa fa-angle-left pull-right"></i> </a>
        <ul class="treeview-menu">
          <li class=""><a href="/sms-setting"><i class="fa fa-arrow-circle-right"></i>SMS Settings</a></li>
          <li class=""><a href="/subscription"><i class="fa fa-arrow-circle-right"></i>Subscription SMS Settings</a></li>
        </ul>
      </li>
    </ul>
  </li>

  <li class="treeview ">
    <a href="#"> <i class="fa fa-cogs"></i> <span>Account Info</span> <i class="fa fa-angle-left pull-right"></i> </a>
    <ul class="treeview-menu">
      <li class=""><a href="buy-units"><i class="fa fa-arrow-circle-right"></i> Buy Units</a></li>
      <li class=""><a href="/account-details"><i class="fa fa-arrow-circle-right"></i>Account Details</a></li>
      <li class=""><a href="/users"><i class="fa fa-arrow-circle-right"></i>Account Users</a></li>
    </ul>
  </li>
</ul>

I tried with this javascript code but ends up opening all the dropdowns. All the same, it does highlight the current item. But I would want the other items remain closed and only active remains open.

<script>
    $(document).ready(function() {
        var url = window.location; 
        var element = $('ul.sidebar-menu a').filter(function() {
        return this.href == url || url.href.indexOf(this.href) == 0; }).parent().addClass('active');
        if (element.is('li')) { 
             element.addClass('active').parent().parent('li').addClass('active')
         }
    });
    </script>

/** Try this ** > for sidebar and treeview menu in adminLTE, it will add active when clicked and remove any previous active class /** to add active class and remove previously clicked menu */

var url = window.location;
// for sidebar menu but not for treeview submenu
$('ul.sidebar-menu a').filter(function() {
    return this.href == url;
}).parent().siblings().removeClass('active').end().addClass('active');
// for treeview which is like a submenu
$('ul.treeview-menu a').filter(function() {
    return this.href == url;
}).parentsUntil(".sidebar-menu > .treeview-menu").siblings().removeClass('active menu-open').end().addClass('active menu-open');

Finally I figured it out!

I included the script below;

<script>
 /** add active class and stay opened when selected */
var url = window.location;

// for sidebar menu entirely but not cover treeview
$('ul.sidebar-menu a').filter(function() {
   return this.href == url;
}).parent().addClass('active');

// for treeview
$('ul.treeview-menu a').filter(function() {
   return this.href == url;
}).parentsUntil(".sidebar-menu > .treeview-menu").addClass('active');
    </script>

Then included <a href="#"> </a> on all <ul class="treeview-menu"> I believe this prevented the lists from opening unless clicked.

This ultimately sorted everything.

Please check below-mentioned solution :

<script type="text/javascript">
   $(document).ready(function(){
  var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
  $('.treeview-menu li').removeClass('active');
  $('[href$="'+url+'"]').parent().addClass("active");
  $('.treeview').removeClass('menu-open active');
  $('[href$="'+url+'"]').closest('li.treeview').addClass("menu-open active");
});
</script>

Try this:v2.3.0

    var url = window.location;

// for sidebar menu entirely but not cover treeview
        $('ul.sidebar-menu a').filter(function() {
            return this.href == url;
        }).parent().addClass('active');

// for treeview
        $('ul.treeview-menu a').filter(function() {
            return this.href == url;
        }).parentsUntil(".sidebar-menu > .treeview-menu").addClass('active');

NOTE: This code for new AdminLTE 3 dev with bootstrap 4

var url = window.location;
const allLinks = document.querySelectorAll('.nav-item a');
const currentLink = [...allLinks].filter(e => {
  return e.href == url;
});

currentLink[0].classList.add("active")
currentLink[0].closest(".nav-treeview").style.display="block";
currentLink[0].closest(".has-treeview").classList.add("active");

If anyone need to fix this on Admin LTE 4 this is working:

<script>
    /** add active class and stay opened when selected */
    var url = window.location;

    // for sidebar menu entirely but not cover treeview
    $('ul.nav-sidebar a').filter(function() {
        return this.href == url;
    }).addClass('active');

    // for treeview
    $('ul.nav-treeview a').filter(function() {
        return this.href == url;
    }).parentsUntil(".nav-sidebar > .nav-treeview").addClass('menu-open').prev('a').addClass('active');
</script>

Adminlte4

$(document).ready(function(){
    const url = window.location;

    $('ul.nav-sidebar a').filter(function() {
        return this.href == url;
    }).parent().addClass('active');

    $('ul.nav-treeview a').filter(function() {
        return this.href == url;
    }).parentsUntil(".sidebar-menu > .nav-treeview").addClass('menu-open');

    $('ul.nav-treeview a').filter(function() {
        return this.href == url;
    }).addClass('active');

    $('li.has-treeview a').filter(function() {
        return this.href == url;
    }).addClass('active');

    $('ul.nav-treeview a').filter(function() {
        return this.href == url;
    }).parentsUntil(".sidebar-menu > .nav-treeview").children(0).addClass('active');

});

This a follow up to GMK Hussain answer for AdminLTE 3. I ran into the null issue and undefined in his code(undefined because I have some pages that are not in nav links at all). I would get jS console errors. Here is what I am using:

 $(document).ready(function () { var url = window.location; const allLinks = document.querySelectorAll('.nav-item a'); const currentLink = [...allLinks].filter(e => { return e.href == url; }); //fix for "cannot read property 'style' of null" on windows.location urls not in the nav, indefined on edit/create pages with id number if (typeof currentLink[0] !== 'undefined') { if (currentLink[0].closest(".nav-treeview") !== null) { currentLink[0].classList.add("active"); currentLink[0].closest(".nav-treeview").style.display = 'block'; currentLink[0].closest(".has-treeview").classList.add("active"); currentLink[0].closest(".has-treeview").classList.add("menu-open"); } } });

I also added: currentLink[0].closest(".has-treeview").classList.add("menu-open"); This will toggle the collapsing of the higher level item possible, without it you had to click the higher level nav twice before it would toggle close.

I don't want this question to be polluted by another answer but none of them worked for AdminLTE-3.0.1.So I created an updated solution.Here is

const url = window.location;
/*remove all active and menu open classes(collapse)*/
$('ul.nav-sidebar a').removeClass('active').parent().siblings().removeClass('menu-open');
/*find active element add active class ,if it is inside treeview element, expand its elements and select treeview*/
$('ul.nav-sidebar a').filter(function () {
    return this.href == url;
}).addClass('active').closest(".has-treeview").addClass('menu-open').find("> a").addClass('active');

Solution without JQuery :

JS Code :

function isActiveElement (route, device, domain, classAsked) {

  var pathName = window.location.pathname;
  var routeName = pathName.split("/")[1];
  var deviceName = pathName.split("/")[2];
  var domainName = pathName.split("/")[3];
  var className = ""

  if(route !== "" && routeName === route) {
    className = classAsked;
  }
  if(domain !== "" && domainName !== domain) {
    className = "";
  }
  if(device !== "" && deviceName !== device) {
    className = "";
  }

  return className;
}

HTML Code :

<li className={"nav-item has-treeview " + isActiveElement(route, "", domain,  "menu-open")}>
        <a href="#" className={"nav-link " + isActiveElement(route, "", domain, "active")}>

I'm using this code to add active class depending of the page.

This is working ok except for multi level submenus any clue how to fix this,

add active class and stay opened when selected

 var url = window.location;
  // for sidebar menu entirely but not cover treeview
  $('ul.sidebar-menu a').filter(function() {
  return this.href == url;
  }).parent().addClass('active');
  // for treeview
  $('ul.treeview-menu a').filter(function() {
  return this.href == url;
  }).closest('.treeview').addClass('active');

      **HTML**
  <li class="treeview">
     <a href="#">
     <i class="fa fa-gears"></i>
     <span>Settings</span>
     <i class="fa fa-angle-left pull-right"></i>
     </a>
     <ul class="treeview-menu">
        <li>
           <a href="#">
           <i class="fa fa-bars"></i>
           Specials Settings
           </a>
           <ul class="treeview-menu">
              <li><a href="setting1.php">Setting 1</a></li>
           </ul>
        </li>
     </ul>
  </li>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM