0

I want to change the active item at my bootstrap navbar. I found this question about the same problem: Bootstrap navbar Active State not working

I almost tried all of the given solution, but none of them worked for me, and I do not understand why. Of course where it needed I changed the class names in the code, but still nothing.

Here is my navbar:

<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand">BRAND</a>
    <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav">
            <li class="nav-item active">
                <a class="nav-link" href="<?= base_url().'index.php/home'; ?>"><?php echo $this->lang->line('home'); ?></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="<?= base_url().'index.php/about'; ?>"><?php echo $this->lang->line('about'); ?></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="<?= base_url().'index.php/contact'; ?>"><?php echo $this->lang->line('contact'); ?></a>
            </li>
        </ul>
    </div>
</nav>

And one of the js that I tried:

$(document).ready(function() {
    $(document).on('click', '.nav-item a', function (e) {
        $(this).parent().addClass('active').siblings().removeClass('active');
    }); 
});

I'm thinking about the problem is maybe that I reload this navbar, when I change a page, and it is overwrite the good navbar, with this basic. But if it is the problem, How can I manage it. I'm new in js and css.

AME
  • 302
  • 2
  • 17

1 Answers1

0

Try this way first remove the active class from all li and after that add in current li

$(document).ready(function() {
    $(document).on('click', '.nav-item a', function (e) {
        $('.nav-item').removeClass('active');
        $(this).parent().addClass('active');
    });
});

  • Not working. It can be the problem, that I reload the navbar with the new page? – AME Aug 06 '19 at 15:18
  • Ohh okay. so if your page is reloaded on change navbar then you have to save active nav local storage if you want to do it via js – Vikramjit SIngh Aug 06 '19 at 15:23