简体   繁体   中英

How to highlight the selected navigation menu in SB-Admin bootstrap Template?

I am using SB-ADMIN bootstrap template in my project. I want to high light the selected Menu. I tried this code, the navigation menu will be highlighted But the right side container it's not loaded. Please find the attached file.

$("#exampleAccordion").on("click", function(event){
    $("#exampleAccordion").find("li").removeClass('active');
    $(event.target).closest("li").addClass('active');
    event.preventDefault();
});

在此处输入图片说明

Its better to handle it in the script side. If you still want to use js for it, then use the following code. This should be attached to each page.

Assumes that you are using relative url for menu link. like /abc/cdf/chart.html . If not change the logic in the $(this).attr('href') == window.location.pathname condition

$(document).ready(function(){
    $("#exampleAccordion a").each(function (index, element) {
        if ($(this).attr('href') == window.location.pathname) {
            $(this).parent().addClass("active");
        }
    });
});

The code will check the current url path with the menu urls, and if finds any match, then it will add class( active ) to the parent

Following with the suggestion from @Aneesh but for the SB Admin 2, considering the nested collapsed items, I came up with this:

$(document).ready(function() {
    console.log(window.location.pathname);
    $("#accordionSidebar a").each(function(index, element) {
        if ($(element).attr('href') == window.location.pathname) {
            if ($(element).hasClass('collapse-item') == true) {
                $(element).parent().parent().parent().addClass("active");
                $(element).parent().parent().addClass("show");
                $(element).addClass("active");
            } else {
                $(element).parent().addClass("active");
            }
        }
    });
});

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