1
votes

I have looked for answers here, but none fit my specific issue.

I have a Bootstrap 4 navbar that I need to change the active class for the menu item that is clicked. I have the home link active by default. But when I click another link, nothing happens. When I click it again, the active class if found and removed, but the active class is not added to the item I clicked, and the active class goes back to the home link.

The relevant portion of my navbar:

$(document).ready(function() {
  $('.nav-link').on('click', function() {
    $('.navbar-nav').find('.active').removeClass('active');
    $(this).addClass('active');
  });
});
.active { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="navbar-nav">
  <li class="nav-item">
    <a id="homelink" class="nav-link active" href="index.php">Home<span class="sr-only">(current)</span></a>
  </li>
  <li class="nav-item">
    <a id="aboutlink" class="nav-link" href="about.php">About</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Portfolio</a>
  </li>
</ul>
2
When you click on a link, it navigates to the page in its href attribute (index.php, about.php, or #). When it does that, no other code will run. - Heretic Monkey

2 Answers

0
votes

This is working fine. Check these files whether they are on proper place:

jquery.min.js - version 3.3.1

bootstrap.min.js - version 4.1.3

popper.min.js - version 1.14.3

bootstrap.min.css - version 4.1.3

$(document).ready(function() {
 $('.nav-link').on('click', function(){
  $('.navbar-nav').find('.active').removeClass('active');
  $(this).addClass('active');
 });
});
.active{
  background-color:grey;
  color:black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

<html>
<head>

</head>
<body>
  <ul class="navbar-nav">
  <li class="nav-item">
    <a id="homelink" class="nav-link active" href="#">Home<span class="sr-only">(current)</span></a>
  </li>
  <li class="nav-item">
    <a id="aboutlink" class="nav-link" href="#">About</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Portfolio</a>
  </li>
</ul>

</body>
</html>
0
votes

I have run your code with the cdn versions(jquery.js,popper.js,bootstrap.js) recommended by bootstrap for bootstrap 4 and all seems to be well.Try changing the version of those to the recommended versions as per official bootstrap page https://getbootstrap.com/docs/4.1/getting-started/introduction/