How to keep 'active' class to li tag when redirect to another page?

2k views Asked by At

I have 2 menus manage category and manage product, it turns 'active' when clicks. Problem is, there is button 'add product' under manage product menu, When I go to add product page menu 'manage product' don't keep 'active'.

<aside class="main-sidebar">
    <section class="sidebar">
        <ul class="sidebar-menu">
            <li>
                <a href="manage_category.php">
                <i class="fa fa-table"></i> <span>Manage category</span>
                </a>
            </li>
                <li>
                <a href="manage_products.php">
                <i class="fa fa-table"></i> <span>Manage products</span>
                </a>
            </li>
        </ul>
    </section>
    <!-- /.sidebar -->
</aside>
<script type="text/javascript">

$(document).ready(function() {
    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');
});
</script>
4

There are 4 answers

0
AudioBubble On

I suspect that url (window.location) != this.href in your filter.

this.href will be e.g. manage_products.php but window.location is an object. (Check the MDN docs for window.location). https://developer.mozilla.org/en-US/docs/Web/API/Location

Even window.location.href will still give you the full url. But - window.location.pathname might be close to what you want.

If you debug your code on this line: return this.href == url; and examine the values you will see your problem.

0
Klamius On

you can add hidden link for 'add product' in your menu

<li>
 <a href="manage_products.php">
  <i class="fa fa-table"></i> <span>Manage products</span>
 </a>
 <a href="add_product.php" style="display:none"></a>
</li>

and your javascript code should works as it's

3
Meloman On

Your window.location returns entire url not only the page.

This is working :

$(document).ready(function() {
    var url = location.pathname.split('/').slice(-1)[0];
    jQuery('ul.sidebar-menu a').each(function() {
        if($(this).attr('href') == url)
            $(this).parent().addClass('active');
    });
});
3
Sindhoor On

if "add product" is not different page then Try below code.

var parameter = Sys.WebForms.PageRequestManager.getInstance();
parameter.add_endRequest(function () {
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');

})