dabadaba
dabadaba

Reputation: 9522

Active link menu switch weird behavior (Bootstrap)

I am surprised that Bootstrap doesn't provide a tool to automatize switching the .active class between the different links in a .nav bar.

So I searched and got some helped and tried to apply this script to my menu:

$('.nav li a').on('click', function() {
    alert("class added " + $(this).parent().find('a').attr('href'));
    $(this).parent().parent().find('.active').removeClass('active');
    $(this).parent().addClass('active');
});

This is the HTML:

<nav class="navbar navbar-default">
    <div class="container-fluid">
        <div class="navbar-header">
            <!-- blah blah -->
        </div>
        <div class="collapse navbar-collapse" id="navbar-collapse">
            <ul class="nav navbar-nav">
                <li class="active"><a href="{{ URL::to('/') }}">Home</a></li>
                <li><a href="{{ URL::to('/directions') }}">Directions</a></li>
            </ul>
        </div>
    </div>
</nav>

The weird thing happening is that when I click on Directions the class .active is removed from Home and then goes to Directions, but just for like half a second, and then it goes back to the way it was before.

I "debugged" the targets like this:

$('.nav li a').on('click', function() {
    alert("clicked " + $(this).attr('href'));
    alert("class removed-> " + $(this).parent().parent().find('.active').find('a').attr('href'));
    alert("class added " + $(this).parent().find('a').attr('href'));
    $(this).parent().parent().find('.active').removeClass('active');
    $(this).parent().addClass('active');
});

And when clicking on Directions the output is:

  1. clicked http://localhost:8000/directions
  2. class removed http://localhost:8000
  3. class added http://localhost:8000/directions

So it seems there's nothing wrong with targeting the correct elements.

What's wrong with the script and why is this weird thing happening?

Upvotes: 0

Views: 85

Answers (2)

dabadaba
dabadaba

Reputation: 9522

Since the script didn't work for some reason I ended up doing this for each option in the menu:

<li class="{{ Request::path() == 'directions' ? 'active' : '' }}">

Upvotes: 0

Stephan Wagner
Stephan Wagner

Reputation: 990

There must be something else wrong with your code, the code you posted works as expected. Here is a fiddle:

http://jsfiddle.net/StephanWagner/xnVM9/

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

I removed the collapse classes, so its easier to see in the fiddle, but it also works with the classes.

Upvotes: 1

Related Questions