Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change active class while click to another link in bootstrap use jquery?

I have a html as sidebar, and use Bootstrap.

<ul class="nav nav-list">
    <li class="active"><a href="/">Link 1</a></li>
    <li><a href="/link2">Link 2</a></li>
    <li><a href="/link3">Link 3</a></li>
</ul>

I want to do some thing:

When I click a link such as Link 3, the page content will change to Link 3's content, and the Link 3 will have class active, and remove the active clss in Link 1.

I think this can be implemented in jQuery, and I have searched many question in SO, such as:

  • How to keep an active link in nav list (twitter bootstrap)?
  • Bootstrap CSS Active Navigation

I use this script:

$(document).ready(function () {
    $('.nav li').click(function(e) {

        $('.nav li').removeClass('active');

        var $this = $(this);
        if (!$this.hasClass('active')) {
            $this.addClass('active');
        }
        //e.preventDefault();
    });
});

But most of them use preventDefault, this will prevent the continued action. So it can't change to Link 3's page content.

If I remove the preventDefault statement, when the page load Link 3's content, the active class will back to Link 1.

So Is there any way to solve this problem?

like image 381
Tanky Woo Avatar asked Jul 31 '13 16:07

Tanky Woo


1 Answers

You are binding you click on the wrong element, you should bind it to the a.

You are prevent default event to occur on the li, but li have no default behavior, a does.

Try this:

$(document).ready(function () {
    $('.nav li a').click(function(e) {

        $('.nav li.active').removeClass('active');

        var $parent = $(this).parent();
        $parent.addClass('active');
        e.preventDefault();
    });
});
like image 101
Karl-André Gagnon Avatar answered Sep 21 '22 10:09

Karl-André Gagnon