Jeffrey Juarez
Jeffrey Juarez

Reputation: 11

How do I maintain active tab when navigating to specific page

I have a navbar on my page. How can I make my tabs become active after clicking the on the relative URL links embedded in the nav-bar? Is there jquery or javascript for this? My page refreshes when I click the individual tabs and I'm confused how I can navigate to another page.

<ul class="navbar-nav navbar-right>">
    <li><a href="/reports">Reports</a></li>
    <li><a href="/resources">Resource Center</a></li>           
</ul>

Upvotes: 1

Views: 585

Answers (2)

shumana chowdhury
shumana chowdhury

Reputation: 1882

This may answer your question @Jeffrey

$(".nav a").on("click", function(){ 
    $(".nav").find(".active").removeClass("active"); 
    $(this).parent().addClass("active");
});

There is more accurate solution for you.

<div class="menu">

    <ul>
    <li><a href="~/link1/">LINK 1</a>
    <li><a href="~/link2/">LINK 2</a>
    <li><a href="~/link3/">LINK 3</a>
    </ul>

</div>
    <script>
    $(document).ready(function(){
    $(".menu ul li a").each(function(){
        if($(this).attr("href")=="www.xyz.com/other/link1")
            $(this).addClass("active");
    })
})    
    </script>
    <style>
    .active { color: red; }

    </style>

Upvotes: 4

Abhilash Augustine
Abhilash Augustine

Reputation: 4208

shumana is correct. But, that would not work when your page refreshes on every click.

So the correct way to do this is, you can find anchor tag with current path and add a 'selected' class to it.

$(document).ready(function(){
    var menu = $("a[href*='" + location.pathname + "']");
    menu[0].addClass('active');
});

So, for every page load you should check your current page and set it a class.

Hope this will help you.

Upvotes: 0

Related Questions