How to Active nav bar in bootstrap with jquery

22,668

Change the jQuery script to this:

<script type="text/javascript">
    $(document).ready(function () {
        var url = window.location;
        $('ul.nav a[href="'+ url +'"]').parent().addClass('active');
        $('ul.nav a').filter(function() {
             return this.href == url;
        }).parent().addClass('active');
    });
</script> 
Share:
22,668
Fred
Author by

Fred

Updated on August 02, 2020

Comments

  • Fred
    Fred almost 4 years

    I want make the navbar active when i click it,,

    Here is the jquery i use

    $(document).ready(function () {
            $('.navbar li').click(function(e) {
                $('.navbar li').removeClass('active');
                var $this = $(this);
                if (!$this.hasClass('active')) {
                    $this.addClass('active');
                }
            e.preventDefault();
            });         
        });
    

    But because the preventDefault i can't go to the link that i want. It just make the navbar active, but it's not go to the link that i choose.

    And here is the link code :

    <div class="nav-collapse collapse">
        <ul class="nav">
            <li><a href='<?php echo site_url(' tampilan ') ?>'>Knowledge Base</a>
            </li>
            <li><a href='<?php echo site_url(' ticketing/browse_ticketing ') ?>'>Ticketing</a>
            </li>
            <li><a href='<?php echo site_url(' user/logout ') ?>'>Logout</a>
            </li>
        </ul>
    </div> 
    

    if i dont use preventDefault() the navbar won't active, but if i use it i can't go to the link i want..