How do I automatically set bootstrap 3 nav item to Active

Using JavaScript, I need to automatically set the current page nav menu item to 'active'. In the code below, Page 3 is manually set to 'active'.


<!-- Navbar -->
    <div class="navbar navbar-default" role="navigation" >
      <div class="container"> 
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse"> <span class="sr-only">Toggle navigation</span> <span class="fa fa-bars"></span> </button>
          <a class="navbar-brand" href="index.html"> <img id="logo-header" src="img/logo4.png" width="205" height="53" alt="Logo"> </a> </div>
        
        <!-- START TOP MENU -->      
      <div class="collapse navbar-collapse navbar-responsive-collapse">
        <ul class="nav navbar-nav">
          <li class="dropdown"><a href="index.html">Home</a> </li>
          <li class="dropdown"><a href="Quotes.html" class="dropdown-toggle" data-toggle="dropdown">Quotes</a>
            <ul class="dropdown-menu">
              <li><a href="Page1.html">Page 1</a></li>
              <li><a href="Page2.html">Page 2</a></li>
            </ul>
          </li>
          <li class="dropdown active" ><a href="Page3.html">Page 3</a> </li>
          <li class="dropdown"> <a href="Page4.html">Page 4</a> </li>
          <li class="dropdown"> <a href="Page5.html" class="dropdown-toggle" data-toggle="dropdown"> Page 5</a>
            <ul class="dropdown-menu">
              <li><a href="Page6.html">Page 6</a></li>
              <li><a href="Page7.html">Page 7</a></li>                          
            </ul>
          </li>
          <li class="dropdown"> <a href="Page8.html">Page 8</a> </li>          
          <!-- END TOP MENU -->            
          </ul>
        </div>
        <!--/navbar-collapse--> 
      </div>
    </div>
    <!-- End Navbar --> 

Open in new window



Thanks in advance!
jayschAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Scott Fell, EE MVEDeveloper & EE ModeratorCommented:
<!DOCTYPE html>
<html>
<head>
<style>
.current{color:red;}
</style>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(function(){
$('ul#nav li a').removeClass();
  var pathname = window.location.pathname; 
  $('#nav li a').each(function(){
 
     var h=$(this).attr('href');
	 if (h==pathname){
	    $(this).addClass('current');
	 }
  });
  alert(pathname);
});


</script>
  <meta charset="utf-8">
  <title>padas</title>
</head>
<body>
<ul id="nav">
<li><a href="/first/second/">home</a></li>
<li><a href="/first/second/third">Products</a></li>
</ul>
</body>
</html>

Open in new window

0
jayschAuthor Commented:
Scott,

Thank you for your suggestion but this code is not working for me. It looks like the code removes the default class associated with the active state and adds a new class? Would it be possible for you to mark up my original code with the require modifications?

Thank you.
0
Scott Fell, EE MVEDeveloper & EE ModeratorCommented:
Give this a try to help solve the issue.  I added a div#test to show the path name.  If your url to the page is mydomain.com/shop/products/item1 then the path will be /shop/products/item1.  If the path is mydomain.com/shop/products/item1.html then the path will be /shop/products/item1.html.

In order to make the li active, we need to either match the href you have in the navigation or test if the href is in the text of the url.  

I have commented out the exact match.  The exact match will not work if the href = "page3.html" and the path is /shop/products/page3.html .  The 2nd method where we test if page3.html is in /shop/products/page3.html will work.

If your site is all on one level where all pages are on mysite.com/page3.html then the first method will work.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
    
      <script>
$(function(){
    $('.nav li a').removeClass();
      var pathname = window.location.pathname; 
      $('.nav li a').each(function(){
 
      var h=$(this).attr('href');
      
      // USE THIS TEST TO MATCH EXACT URL PATH
      /*
	  if (h==pathname){
	    //$(this).addClass('active');
	   
	    $(this).parent().addClass("active");
	  }
	  */
	  
	  // USE THIS TEST TO MATCH ANY PORTION OF THE HREF IS IN THE URL PATH
	  if (pathname.indexOf(h)>-1){
	    //$(this).addClass('active');
	   
	    $(this).parent().addClass("active");
	  }
	  
	  
	  
	  $("#info").html("Pathname: "+pathname);
  });
  
});
    </script>
    <meta charset="utf-8">
    <title>padas</title>
</head>
<body>
<!-- Navbar -->
    <div class="navbar navbar-default" role="navigation" >
      <div class="container"> 
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse"> <span class="sr-only">Toggle navigation</span> <span class="fa fa-bars"></span> </button>
          <a class="navbar-brand" href="index.html"> <img id="logo-header" src="img/logo4.png" width="205" height="53" alt="Logo"> </a> </div>
        
        <!-- START TOP MENU -->      
      <div class="collapse navbar-collapse navbar-responsive-collapse">
        <ul class="nav navbar-nav">
          <li class="dropdown"><a href="index.html">Home</a> </li>
          <li class="dropdown"><a href="Quotes.html" class="dropdown-toggle" data-toggle="dropdown">Quotes</a>
            <ul class="dropdown-menu">
              <li><a href="Page1.html">Page 1</a></li>
              <li><a href="Page2.html">Page 2</a></li>
            </ul>
          </li>
          <li class="dropdown" ><a href="Page3.html">Page 3</a> </li>
          <li class="dropdown"> <a href="Page4.html">Page 4</a> </li>
          <li class="dropdown"> <a href="Page5.html" class="dropdown-toggle" data-toggle="dropdown"> Page 5</a>
            <ul class="dropdown-menu">
              <li><a href="Page6.html">Page 6</a></li>
              <li><a href="Page7.html">Page 7</a></li>                          
            </ul>
          </li>
          <li class="dropdown"> <a href="Page8.html">Page 8</a> </li>          
          <!-- END TOP MENU -->            
          </ul>
        </div>
        <!--/navbar-collapse--> 
      </div>
    </div>
    <!-- End Navbar --> 
      <div class="row">
    	<div id="info" class="col-xs-12"></div>
    </div>
</body>
</html>

Open in new window


The code above will set the nav bar to active for pages with only one item such as pages page3.html, page4.html. But for the pages page1.html and page2.html which are under the nav item, "Quotes", the "Quotes" will not be active but if you activate the drop down you can see the individual items are lit up.  If you want to also make the top level nav to active, then you need to light that up as well.  

That can be done by adding
$(this).closest("li.dropdown").addClass("active");

Open in new window

$(function(){
    $('.nav li a').removeClass();
      var pathname = window.location.pathname; 
      $('.nav li a').each(function(){
 
      var h=$(this).attr('href');
      
      // USE THIS TEST TO MATCH EXACT URL PATH
      /*
	  if (h==pathname){
	    //$(this).addClass('active');
	   
	    $(this).parent().addClass("active");
	  }
	  */
	  
	  // USE THIS TEST TO MATCH ANY PORTION OF THE HREF IS IN THE URL PATH
	  if (pathname.indexOf(h)>-1){
	    //$(this).addClass('active');
	   
	    $(this).parent().addClass("active");
	    $(this).closest("li.dropdown").addClass("active");
	  }
	  
	  
	  
	  $("#info").html("Pathname: "+pathname);
  });
  
});

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jayschAuthor Commented:
Scott,

Your solution works great - thanks for the help.
0
Scott Fell, EE MVEDeveloper & EE ModeratorCommented:
Your welcome.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
CSS

From novice to tech pro — start learning today.