Simple jquery function to set active navigation link with Twitter Bootstrap


Usually in a web application you would want the user to know which link is active by highlighting the active link. Twitter Bootstrap has a class

.active

that we can use to do this. This class needs to be applied to an

<li> <a href="#"></a> </li>

tag.

Html Structure

<ul class="nav">
    <li>
        <a href="/Home/Index">Index</a>
    </li>
    <li>
        <a href="/Home/About">About</a>
    </li>
</ul>

Jquery function

$(document).ready(function () {
    $('.nav a').each(function () {
        var url = $(this).attr('href');
        if (currentlocation == url) {
            $(this).closest('li').addClass(&quot;active&quot;);
        }
    });
});

And that’s it! Of course there are a lot many other approaches as well that we can use. This is just a most simplistic to get something up and running in a simple project.

Advertisements