Thursday, December 19, 2013

Bootstrap add active class to li

In the following example, we use a classic Bootstrap menu.Note that, none li had a class active.We will use after.
    <div class="navbar navbar-default span12" role="navigation">
            <...>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a href="/fjLearning/"><g:message code="menu.home" /></a></li>
                    <li><a href="/fjLearning/page/training"><g:message code="menu.training" /></a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown"><g:message code="menu.about" /> <b class="caret"></b></a>
                        <ul class="dropdown-menu">
                            <li><a href="/fjLearning/page/about"><g:message code="menu.about.perso" /></a></li>
                            <li class="divider"></li>
                            <li class="dropdown-header"><g:message code="menu.about.site" /></li>
                            <li><a href="/fjLearning/page/under"><g:message code="menu.underTheHood" /></a></li>
                            <li><a href="#">FAQ</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
    </div>

To make it works you have in each page to add :
<body>
<script>
    $(document).ready(function() {
        $('a[href="' + this.location.pathname + '"]').parent().addClass('active');
    });
</script>
...

Now, when I clicked on the menu, the link active changes automatically. If you want to see an example, go on my GittHub project : https://github.com/drieu/fjLearning

Here is the usefull files :
https://github.com/drieu/fjLearning/blob/master/grails-app/views/layouts/_menu.gsp
https://github.com/drieu/fjLearning/blob/master/grails-app/views/page/training.gsp