101

I have bootstrap v3.

I use the class="active" on mynavbar and it does not switch when I press menu items. I know how to do this with jQuery and build a click function but I'm thinking this functionality should be included in bootstrap? So maybe it is a JavaScript issue?

Here is my header with my js/css/bootstrap files I have included:

<!-- Bootstrap CSS -->
<link rel="stylesheet" href= "/bootstrap/css/bootstrap.css" />
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<link rel="stylesheet" href= "/stylesheets/styles.css" />

<!--jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>

<!-- Bootstrap JS -->
<script src="/bootstrap/js/bootstrap.min.js"></script>
<script src="/bootstrap/js/bootstrap-collapse.js"></script>
<script src="/bootstrap/js/bootstrap-transition.js"></script>

Here is my navbar code:

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbarCollapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

                <a class="navbar-brand" href="/index.php">MyBrand</a>
            </div>

            <div class="collapse navbar-collapse navbarCollapse">
                <ul class="nav navbar-nav navbar-right">
                    <li class="active">
                        <a href="/index.php">Home</a>
                    </li>

                    <li>
                        <a href="/index2.php"> Links</a>
                    </li>

                    <li>
                        <a href="/history.php">About</a>
                    </li>
                    <li>
                        <a href="/contact.php">Contact</a>
                    </li>

                    <li>
                        <a href="/login.php">Login</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

Am I setting this up right?

(On an unrelated note, but possible related? When the menu goes mobile, I click the menu button and it collapses. Pushing it again does not un-collapse it though. So this issue,. with the other, both signify wrong JavaScript setup perhaps?)

TheLettuceMaster
  • 15,594
  • 48
  • 153
  • 259
  • 3
    Since time I work with bootstrap, I think Boostrap don't manage it, you have to set active class yourself... If I'm wrong, I'll learn a lot with it... – BENARD Patrick Jul 01 '14 at 16:12
  • 1
    Well @TheLittlePig is correct, you need to add the `active` class yourself when your application generates the HTML. – DavidG Jul 01 '14 at 16:20

32 Answers32

157

You have included the minified Bootstrap js file and collapse/transition plugins while the docs state that:

Both bootstrap.js and bootstrap.min.js contain all plugins in a single file.
Include only one.

and

For simple transition effects, include transition.js once alongside the other JS files. If you're using the compiled (or minified) bootstrap.js, there is no need to include this—it's already there.

So that could well be your problem for the minimize problem.

For the active class, you have to manage it yourself, but it's just a line or two.

Bootstrap 3:

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

Bootply: http://www.bootply.com/IsRfOyf0f9

Bootstrap 4:

$(".nav .nav-link").on("click", function(){
   $(".nav").find(".active").removeClass("active");
   $(this).addClass("active");
});
Pete TNT
  • 8,293
  • 4
  • 36
  • 45
  • 2
    Does this work if you move from the page to another in `href` (not hash but send another request)? – Blaszard Feb 03 '16 at 03:49
  • 1
    @Blaszard in a non-single page apps/sites you should have `active` class on the `nav` item by default. – Pete TNT Feb 03 '16 at 06:48
  • Does not work for me. The list item never shows up as active!? What am I not doing that you guys are doing? – Dakotah North Apr 21 '16 at 23:20
  • 7
    its not working for me, its getting added but in next second its going to initial active class so it's not staying on the page please anyone help on this – sourav78611 Sep 21 '16 at 05:54
  • I read through all answers thinking, no way Bootstrap won't have this built-in. Like why? – Mahesh Oct 12 '16 at 15:00
  • I marked this down because there is no explanation of where to put the code. I tried it in a script block and it did nothing. – Dave Oct 28 '16 at 21:39
  • @Dave you'll need the code inserted after jQuery, wrapped in a `$(document).ready()` or alternatively use event delegation with `$("body").on("click", ".nav a", function () { ... code ... })`; – Pete TNT Oct 29 '16 at 18:32
  • 15
    @Pete TNT - It's still not clear and it's very frusterating when people give 90% of a soloution and assume everyone knows how to apply the remaining 10%. Especially in scenarios when syntax is hard to get right. – Dave Oct 31 '16 at 17:07
  • @Dave that is fair enough, but this particular answer is for the question the OP asked. While the answer is beneficial for other use cases too, more in-depth explanations might be better suited for something like SO Documentation (http://stackoverflow.com/documentation/twitter-bootstrap/). – Pete TNT Oct 31 '16 at 19:07
  • Good solution. I had an event listener already attached to the `a`s with `$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { ...` and `$(".nav a").on("click"` didn't work; what did though was using the code inside `.on("show.bs.tab", function(){ ...`. – Majid Fouladpour Jun 05 '17 at 08:23
  • @sourav78611 im ahaving the exact same issue. did you get it right? its driving me nuts – loekTheDreamer Oct 27 '17 at 08:10
  • I don't think this approach works with Bootstrap 4, since now it is the parent `li` element which holds the `active` class css attribute – information_interchange Mar 09 '18 at 04:29
  • @information_interchange thanks, added a BS4 example too – Pete TNT Mar 09 '18 at 08:44
  • 3
    @sourav78611 because you are refreshing the page when you click on the link. This solution will work for the ajax request. For non-ajax requests solution below by Jon works. – A P Jul 25 '18 at 21:04
  • @information_interchange See my answer for Bootstrap 4 solution. This indeed will not work. – Michelangelo Jul 08 '19 at 18:46
  • You should also set `aria-current="page"` for the active menu item, to mark it for assistive technologies, if it’s a page navigation. Maybe simply `.removeClass('active').removeAttr('aria-current');` and `.addClass('active').attr('aria-current', 'page');` – Andy Jul 18 '22 at 15:31
112

Here was my solution for switching active pages

$(document).ready(function() {
  $('li.active').removeClass('active').removeAttr('aria-current');
  $('a[href="' + location.pathname + '"]').closest('li').addClass('active').attr('aria-current', 'page'); 
});
Jon
  • 1,954
  • 1
  • 15
  • 13
  • 2
    Where should we put this? Sorry; new to JS :# – mrateb Dec 26 '17 at 17:20
  • 3
    This works fine in Bootstrap 4. @Thomas8: this should go between ` tags at the bottom of the html file before the `

    ` tag (assuming you have everything in one html file).

    – alwaysCurious Mar 03 '18 at 21:22
  • added the same in site.js without any – Oracular Man Apr 21 '18 at 17:55
  • For me this was the only solution that worked on bootstrap 3.3.7 many thanks. – MitchellK Apr 27 '18 at 11:16
  • This solution eventually worked for me. I added in the function: console.log(location.pathname) and realized, in the , then this function works for making the right "li" active on navbar. – Emily Oct 12 '18 at 03:11
  • So it's a workaround to recover from Boostrap bug that exist in both bootstrap 3 and 4 ?? – GyRo Nov 06 '18 at 14:53
  • Hello GyRo. Handling active pages for a multi-page app vs. active pages for a single page app would look different. I would consider this design decision to be outside of the bootstrap framework. Bottom line, I do not believe this is a bug. It is a decision the UI designer needs to make. – Jon Nov 07 '18 at 14:29
  • 1
    I am using bootstrap 4 and This worked for me. Thank you – Qwerty Feb 29 '20 at 12:45
  • 1
    Works perfectly! In case the menu url contains search params, please replace `location.pathname` with `location.pathname + location.search` to make it work! – xjlin0 Apr 17 '20 at 15:02
  • works perfectly for bootstrap4, flask render_template(), non-ajax refresh – Randy Welt Aug 06 '21 at 22:58
  • 1
    You should also set `aria-current="page"` for the active menu item, to mark it for assistive technologies, if it’s a page navigation. Maybe simply `.removeClass('active').removeAttr('aria-current');` and `.addClass('active').attr('aria-current', 'page');` – Andy Jul 18 '22 at 15:30
20

This worked perfectly for me, because "window.location.pathname" also contains data before the real page name, e.g. directory/page.php. So the actual navbar link will only be set to active if the url contains this link.

$(document).ready(function() {
    $.each($('#navbar').find('li'), function() {
        $(this).toggleClass('active', 
            window.location.pathname.indexOf($(this).find('a').attr('href')) > -1);
    }); 
});
SemperFi
  • 190
  • 2
  • 14
Bettelbursche
  • 433
  • 6
  • 14
14

With version 3.3.4 of bootstrap, on long html pages you can refer to sections of the pg. by class or id to manage the active navbar link with spy-scroll with the body element:

  <body data-spy="scroll" data-target="spy-scroll-id">

The data-target will be a div with the id="spy-scroll-id"

    <div id="spy-scroll-id" class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#topContainer">Home</a></li>
        <li><a href="#details">About</a></li>
        <li><a href="#carousel-container">SlideShow</a></li>
      </ul>
    </div>

This should activate links by clicking without any javascript functions needed and will also automatically activate each link as you scroll through the corresponding linked sections of the page which a js onclick() will not.

jim
  • 196
  • 1
  • 5
  • 1
    Thanks. It should be: data-target="#spy-scroll-id" and not data-target="spy-scroll-id" – Vdex Apr 23 '16 at 22:26
11

All you need to do is simply add data-toggle="tab" to your link inside bootstrap navbar like this:

<ul class="nav navbar-nav">
  <li class="active"><a data-toggle="tab" href="#">Home</a></li>
  <li><a data-toggle="tab" href="#">Test</a></li>
  <li><a data-toggle="tab" href="#">Test2</a></li>
</ul>
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
  • this is really useful, but it doesn't work when you have a navbar-nav (normal) and _also_ a navbar-right second list. You end up with two active that aren't ever cleared – Karl P Dec 15 '16 at 22:49
  • 5
    when I add "data-toggle", the page can't go to the "#place" specified in href. – scorpiozj Mar 24 '17 at 03:04
  • Actually an update. As @scorpiozj mentioned. When this is added the link itself does not work – mrateb Dec 26 '17 at 17:26
9

If you don't use anchor links, you can use something like this:

$(document).ready(function () {
    $.each($('#navbar').find('li'), function() {
        $(this).toggleClass('active',
            '/' + $(this).find('a').attr('href') == window.location.pathname);
    });
});
Zitrax
  • 19,036
  • 20
  • 88
  • 110
6

With Bootstrap 4 you can use this:

$(document).ready(function() {
    $(document).on('click', '.nav-item a', function (e) {
        $(this).parent().addClass('active').siblings().removeClass('active');
    });
});
Carlos Cuesta
  • 1,262
  • 1
  • 17
  • 20
5

This elegant solution did the trick for me. Any new ideas/suggestions are welcome.

$( document ).on( 'click', '.nav-list li', function ( e ) {
    $( this ).addClass( 'active' ).siblings().removeClass( 'active' );
} );

You can use jQuery's "siblings()" method to keep only the accessed item active and its siblings inactive.

JefferinJoseph
  • 151
  • 2
  • 6
5

I use this. It's short, elegand and easy to understand.

$(document).ready(function() {
    $('a[href$="' + location.pathname + '"]').addClass('active');
});
Evaldas
  • 51
  • 1
  • 2
2

I've been struggling with this today, data-togle only worked if I'm on a single page application.

I'm not using ajax to load the content i'm actually making post request for other pages so the first js script was useless too. I solve it with this lines:

var active = window.location.pathname;
$(".nav a[href|='" + active + "']").parent().addClass("active");
2

Bootstrap 4: navbar Active State working, just use .navbar-nav .nav-link classes

 $(function () {
  // this will get the full URL at the address bar
  var url = window.location.href;
  // passes on every "a" tag
  $(".navbar-nav .nav-link").each(function () {
    // checks if its the same on the address bar
    if (url == (this.href)) {
      $(this).closest("li").addClass("active");
      //for making parent of submenu active
      $(this).closest("li").parent().parent().addClass("active");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item">
        <a class="nav-link" href="#">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">


        <a class="nav-link" href="#">Other</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>
2

Vanilla JS solution for Bootstrap 5

document.addEventListener("DOMContentLoaded", function () {
    // make all currently active items inactive
    // (you can delete this block if you know that there are no active items when loading the page)
    document.querySelectorAll("a.nav-link.active").forEach(li => {
        li.classList.remove("active");
        li.attributes.removeNamedItem("aria-current");
    });

    // find the link to the current page and make it active
    document.querySelectorAll(`a[href="${location.pathname}"].nav-link`).forEach(a => {
        a.classList.add("active");
        a.setAttribute("aria-current", "page");
    });
});
bb1950328
  • 1,403
  • 11
  • 18
1

I'm hope this will help to solve this problem.

      var navlnks = document.querySelectorAll(".nav a");
        Array.prototype.map.call(navlnks, function(item) {

            item.addEventListener("click", function(e) {

                var navlnks = document.querySelectorAll(".nav a"); 

                Array.prototype.map.call(navlnks, function(item) {

                    if (item.parentNode.className == "active" || item.parentNode.className == "active open" ) {

                        item.parentNode.className = "";

                    } 

                }); 

                e.currentTarget.parentNode.className = "active";
            });
        });
Kirill Shur
  • 280
  • 2
  • 4
1

I had some pain with this, using a dynamically generated list items - WordPress Stack.

Added this and it worked:

$(document).ready(function () {
    $(".current-menu-item").addClass("active");
});

Will do it on the fly.

Someguywhocodes
  • 781
  • 5
  • 17
1

I've been looking for a solution that i can use on bootstrap 4 navbars and other groups of links.

For one reason or another most solutions didn't work especially the ones that try to add 'active' to links onclick because of course once the link is clicked if it takes you to another page then the 'active' you added won't be there because the DOM has changed. Many of the other solutions didn't work either because they often did not match the link or they matched more than one.

This elegant solution is fine for links that are different ie: about.php, index.php, etc...

$(function() {
   $('nav a[href^="' + location.pathname.split("/")[2] + '"]').addClass('active');
});

However when it came to the same links with different query strings such as index.php?tag=a, index.php?tag=b, index.php?tag=c it would set all of them to active whichever was clicked as it's matching the pathname not the query as well.

So i tried this code which matched the pathname and the query string and it worked on all the links with query strings but when a link like index.php was clicked it would set the similar query string links active as well. This is because my function is returning an empty string if there is no query string in the link, again just matching the pathname.

$(function() {
   $('nav a[href^="' + location.pathname.split("/")[2] + returnQueryString(location.href.split("?")[1]) + '"]').addClass('active');
});
/** returns a query string if there, else an empty string */
function returnQueryString (element) {
   if (element === undefined)
      return "";
   else
      return '?' + element;
}

So in the end i abandoned this route and kept it simple and wrote this.

$('.navbar a').each(function(index, element) {
    //console.log(index+'-'+element.href);
    //console.log(location.href);
    /** look at each href in the navbar
      * if it matches the location.href then set active*/
    if (element.href === location.href){
        //console.log("---------MATCH ON "+index+" --------");
        $(element).addClass('active');
    }
});

It works on all links with or without query strings because element.href and location.href both return the full path. For other menus etc you can simply change the parent class selector (navbar) for another ie:

$('.footer a').each(function(index, element)...

One last thing which also seems important and that is the js & css library's you are using however that's another post perhaps. I hope this helps and contributes.

Steve Whitby
  • 403
  • 4
  • 8
0

Class "active" is not managed out of the box with bootstrap. In your case since you're using PHP you can see:

How add class='active' to html menu with php

to assist you with a method of mostly automating it.

Community
  • 1
  • 1
Kritner
  • 13,557
  • 10
  • 46
  • 72
0

For bootstrap mobile menu un-collapse after clicking a item you can use this

$("ul.nav.navbar-nav li a").click(function() {    

    $(".navbar-collapse").removeClass("in");
});
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
Nurul Amin
  • 11
  • 2
0

I m using bootstrap bare theme, here is the sample navbar code. Note the class name of the element -> .nav - as this is referred in java script.

/ Collect the nav links, forms, and other content for toggling
    #bs-example-navbar-collapse-1.collapse.navbar-collapse
      %ul.nav.navbar-nav
        %li
          %a{:href => "/demo/one"} Page One
        %li
          %a{:href => "/demo/two"} Page Two
        %li
          %a{:href => "/demo/three"} Page Three

in the view page (or partial) add this :javascript, this needs to be executed every time page loads.

haml view snippet ->

- content_for :javascript do
  :javascript
      $(function () {
          $.each($('.nav').find('li'), function() {
              $(this).toggleClass('active',
                  $(this).find('a').attr('href') == window.location.pathname);
          });
      });

In the javascript debugger make sure you have value of 'href' attribute matches with window.location.pathname. This is slightly different than the solution by @Zitrax which helped me fixing my issue.

Rishi
  • 5,869
  • 7
  • 34
  • 45
0

For AngularJS, you can use ng-class with a function like this:

HTML ->

<nav class="navbar navbar-default" ng-controller="NavCtrl as vm">
  <div class="container">
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav" >
        <li ng-class="vm.Helper.UpdateTabActive('Home')"><a href="#" ng-click>Home</a></li>
        <li ng-class="vm.Helper.UpdateTabActive('About')"><a href="#about">About</a></li>
        <li ng-class="vm.Helper.UpdateTabActive('Contact')"><a href="#contact">Contact</a></li>        
      </ul>
    </div>
</nav>

And controller

app.controller('NavCtrl', ['$scope', function($scope) {
    var vm = this;
    vm.Helper = {
        UpdateTabActive: function(sTab){
            return window.location.hash && window.location.hash.toLowerCase() == ("#/" + sTab).toLowerCase() ? 'active' : '';
        }
    }    
}]);

If you are using $location, then there won't be hash. So you can extract the required string from URL using $location

Following will not work in all cases -->

Using a scope variable like following will work only when clicked, but if the transition is done using $state.transitionTo or window.location or manually updating the URL, the Tab value will not be updated

<ul class="nav navbar-nav" ng-init="Tab='Home'">
   <li ng-class="Tab == 'Home' ? 'active' : ''"><a href="#" ng-click="Tab = 'Home'">Home</a></li>
   <li ng-class="Tab == 'About' ? 'active' : ''"><a href="#" ng-click="Tab = 'About'">About</a></li>
</ul>
Mahesh
  • 3,727
  • 1
  • 39
  • 49
0

Add this JavaScript on your main js file.

$(".navbar a").on("click", function(){
      $(".navbar").find(".active").removeClass("active");
      $(this).parent().addClass("active");
    });
0

I had to go a step forward because my file names were not the same as my nav bar titles. i.e. my first nav bar link was HOME but the file name is index..

So just grab the pathname and match it.

Obviously this is a crude example and could be more efficient but it is highly custom need.

var loc_path = location.pathname;
$('li.active').removeClass('active');



if(loc_path.includes('index')){
    $('li :eq(0)').addClass('active');
}else if(loc_path.includes('blog')){
    $('li :eq(2)').addClass('active');
}else if(loc_path.includes('news')){
    $('li :eq(3)').addClass('active');
}else if(loc_path.includes('house')){
    $('li :eq(4)').addClass('active');
}
Cparello
  • 607
  • 6
  • 8
0

Bootstrap 4 solution that worked for me:

$(document).ready(function() {
//You can name this function anything you like
function activePage(){
//When user lands on your website location.pathname is equal to "/" and in 
//that case it will add "active" class to all links
//Therefore we are going to remove first character "/" from the pathname
  var currentPage = location.pathname;
  var slicedCurrentPage = currentPage.slice(1);
//This will add active class to link for current page
  $('.nav-link').removeClass('active');
  $('a[href*="' + location.pathname + '"]').closest('li').addClass('active');
//This will add active class to link for index page when user lands on your website
     if (location.pathname == "/") {
         $('a[href*="index"]').closest('li').addClass('active');
    }
}
//Invoke function
activePage();
});

This will only work if href contains location.pathname!

If you are testing your site on your own pc (using wamp, xampp, lamp, etc...) and your site is located in some subfolder then your path is actually "/somefolder/something.php", so don't get confused.

I would suggest if you are unsure to use following code so you can make sure what is the correct location.pathname:

$(document).ready(function() {
  alert(location.pathname);
});
Luka Sh
  • 340
  • 7
  • 11
0

the next answer is for those who have a multi-level menu:

var url = window.location.href;

var els = document.querySelectorAll(".dropdown-menu a");
for (var i = 0, l = els.length; i < l; i++) {
    var el = els[i];
    if (el.href === url) {
       el.classList.add("active");
       var parent = el.closest(".main-nav"); // add this class for the top level "li" to get easy the parent
       parent.classList.add("active");
    }
}

Exeample how it works

futur1st
  • 61
  • 1
  • 11
0

As someone who doesn't know javascript, here's a PHP method that works for me and is easy to understand. My whole navbar is in a PHP function that is in a file of common components I include from my pages. So for example in my 'index.php' page I have... `

<?php
   $calling_file = basename(__FILE__);
   include 'my_common_includes.php';    // Going to use my navbar function "my_navbar"
   my_navbar($calling_file);    // Call the navbar function
 ?>

Then in the 'my_common_includes.php' I have...

<?php
   function my_navbar($calling_file)
   {
      // All your usual nabvbar code here up to the menu items
      if ($calling_file=="index.php")   {   echo '<li class="nav-item active">';    } else {    echo '<li class="nav-item">';   }
    echo '<a class="nav-link" href="index.php">Home</a>
</li>';
      if ($calling_file=="about.php")   {   echo '<li class="nav-item active">';    } else {    echo '<li class="nav-item">';   }
    echo '<a class="nav-link" href="about.php">About</a>
</li>';
      if ($calling_file=="galleries.php")   {   echo '<li class="nav-item active">';    } else {    echo '<li class="nav-item">';   }
    echo '<a class="nav-link" href="galleries.php">Galleries</a>
</li>';
       // etc for the rest of the menu items and closing out the navbar
     }
  ?>
M61Vulcan
  • 337
  • 3
  • 7
0

Bootstrap 4 requires you to target the li item for active classes. In order to do that you have to find the parent of the a. The 'hitbox' of the a is as big as the li but due to bubbeling of event in JS it will give you back the a event. So you have to manually add it to its parent.

  //set active navigation after click
  $(".nav-link").on("click", (event) => {
    $(".navbar-nav").find(".active").removeClass('active');
    $(event.target).parent().addClass('active');
  });
Michelangelo
  • 5,888
  • 5
  • 31
  • 50
0

I tried about first 5 solutions and different variations of them, but they didn't work for me.

Finally I got it working with these two functions.

$(document).on('click', '.nav-link', function () {
    $(".nav-item").find(".active").removeClass("active");
})

$(document).ready(function() {
    $('a[href="' + location.pathname + '"]').closest('.nav-item').addClass('active'); 
});
Jukka S.
  • 51
  • 5
0

when use header.php for every page for the navbar code, the jquery does not work, the active is applied and then removed, a simple solution, is as follows

on every page set variable <?php $pageName = "index"; ?> on Index page and similarly <?php $pageName = "contact"; ?> on Contact us page

then call the header.php (ie the nav code is in header.php) <?php include('header.php'); >

in the header.php ensure that each nav-link is as follows

<a class="nav-link <?php if ($page_name == 'index') {echo "active";} ?> href="index.php">Home</a>

<a class="nav-link <?php if ($page_name == 'contact') {echo "active";} ?> href="contact.php">Contact Us</a>

hope this helps cause i have spent days to get the jquery to work but failed,

if someone would kindly explain what exactly is the issue when the header.php is included and then page loads... why the jquery fails to add the active class to the nav-link..??

0

For Bootstrap 5 I use the folowing to keep the dropdown items active after navigating to a url.

 <li class="nav-item dropdown text-center ">
          <a class="nav-link dropdown-toggle dropdown-toggle-split" href="#" id="navbarDropdown1" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            Clienten
          </a>
          <ul class="dropdown-menu" aria-labelledby="navbarDropdown1">
          <li><h6 class="dropdown-header">Iedereen</h6></li>
            <li><a class="dropdown-item " aria-current="page" href="/submap/IndexClients.php">Overzicht</a></li>
            
            <li><hr class="dropdown-divider"></li>
            <li><h6 class="dropdown-header">Persoonlijk</h6></li>
            <li><a class="dropdown-item" aria-current="page" href="/submap/IndexClientsP.php">Overzicht (<?= $usernamesession ?>)</a></li>
            
          </ul>
        </li>

<script>
$(document).ready(function() {

  $('a.active').removeClass('active');
var active = window.location.pathname;
    $('a[href="' + active + '"]').closest('.dropdown-item').addClass('active'); 
});

</script>
Martin4523
  • 107
  • 10
0

Bootstrap 5.1

This is already implemented in bootstrap, and explained neatly in the documentation under the scrollspy section. Link to documentation

Steps to fix active state toggle:

  1. set position:relative on your body element
  2. add id="navbar" to your navbar section.
  3. include this in your js file, or inside in the html:
var scrollSpy = new bootstrap.ScrollSpy(document.body, {
  target: '#navbar'
})
eva
  • 57
  • 9
  • According to the docs the ScrollPy is for activate menu items based on scroll position, not on the current url – Aikanáro Jan 03 '23 at 18:38
0

With bootstrap 4 I missed from the documentation that I needed to also add

$('#myList a').on('click', function (e) {
    e.preventDefault()
    $(this).tab('show')
})

https://getbootstrap.com/docs/4.0/components/list-group/

Matt Doran
  • 2,050
  • 2
  • 16
  • 18
0

alot of people need a jq/js solution for non ajax-request for bs4 so i ve worked my way to this solution that works just fine first we get the currant path stripped from all queries and have it stored second we loop through nav-links attribute values after we check that they aren't empty finally we do a match between the values and the path) P.S : we don't need to check for an existing active class since this is non ajax-request so make sure u don't hard code an active class in ur html

    $(function(){
    let path = location.pathname.split('/').pop();
    $('#mainNav li a').each(function(){
        var $this = $(this);
        if ($this.length > 0) {
            var hrefValue = $this.attr("href").split('?')[0];
            if(hrefValue == path)
            {
                $this.addClass('active');
            }
        }
    })
})
0

Change your class

<li class="nav-item active">
   <a href="contact.php" class="nav-link">Contact</a>
</li>

and add in your .css, with properties equals of your :hover:

  #navbar .active a{
    color:rgb(150, 0, 0);
    text-decoration: none;
    font-weight: bold;   
  }