Reputation: 85
I am really new with bootstrap, and I'm trying to apply the active class to a menu, but for some reason is not working, I don't know if it is the jquery function (I got it from a tutorial) or if bootstrap won't allow the use of active links.
HTML
<div class="masthead">
<nav id="topNav" role="navigation" aria-label="Top Navigation">
<ul class="nav nav-justified">
<li><a href="../index.html">Home</a></li>
<li><a href="../cars.html">Cars</a></li>
<li><a href="../model.html">Models</a></li>
<li><a href="../colors.html">Colors</a></li>
</ul>
</nav> <!-- /Top Navigation -->
</div> <!-- /masthead -->
CSS
nav-justified a.activee {
background:red !important;
}
JS
jQuery(function() {
jQuery('.nav-justified a').each(function() {
if (jQuery(this).attr('href') === window.location.pathname) {
jQuery(this).addClass('activee');
}
});
});
Upvotes: 0
Views: 162
Reputation: 3156
if you use twitter-bootstrap 3,can use this code :
<div class="navbar navbar-inverse navbar-static-top">
<div class="container-fluid">
<ul class="nav navbar-nav navbar-left">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">CARS</a></li>
<li><a href="#">MODEL</a></li>
<li><a href="#">COLORS</a></li>
</ul>
</div>
</div>
and use class="active"
in li tag to show active page
Upvotes: 1
Reputation: 319
In your JavaScript code you're checking to make sure that the href
attribute of your link is equal to window.location.pathname
but, in your JSFiddle, none of the links have a matching attribute. Try this instead:
<div class="masthead">
<nav id="topNav" role="navigation" aria-label="Top Navigation">
<ul class="nav nav-justified">
<li><a href="/021qbcvd/7/show/">Home</a></li>
<li><a href="../cars.html">Cars</a></li>
<li><a href="../model.html">Models</a></li>
<li><a href="../colors.html">Colors</a></li>
</ul>
</nav> <!-- /Top Navigation -->
</div> <!-- /masthead -->
http://jsfiddle.net/021qbcvd/7/
Note that window.location.pathname
is equal to everything after the main URL. I had to do an alert(window.location.pathname)
to get the correct one for the JSFiddle.
Upvotes: 1