I'm currently building a site with bootstrap and would like to know if it's possible to, and how to add the class="active" attribute to a link on the nav menu. I saw another post similar to this on this very site, however it didn't work on the page using the Bootstrap carousel. I removed all links to jQuery and other javascript on the page but it still wasn't working.
On each page the nav is called with a php include, as is the code for the link state. So picture the markup like so:
<head>
<?php include_once('head.php'); ?>
</head>
<body>
<?php include_once('nav.php'); ?>
</body>
in the head.php is the following code, which I got from another post on this site:
<script>
/*menu handler*/
$(function(){
function stripTrailingSlash(str) {
if(str.substr(-1) == '/') {
return str.substr(0, str.length - 1);
}
return str;
}
var url = window.location.pathname;
var activePage = stripTrailingSlash(url);
$('.nav li a').each(function(){
var currentPage = stripTrailingSlash($(this).attr('href'));
if (activePage == currentPage) {
$(this).parent().addClass('active');
}
});
});
</script>
and in the nav.php I've got:
<nav class="navbar navbar-fixed-top navbar-default" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php"><img src="assets/img/logo.png" /></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><a href="/template.php">About</a></li>
<li><a href="/index-template.php">Services</a></li>
<li><a href="/index.php">Home</a> </li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
Each page is named as per the href attr.
This works on a duplicate of template.php, however it doesn't work on index.php, which is making me think it's something to do with the carousel...
I've also tried using the data-toggle="pill" as recommended somewhere but that doesn't work.
Any assistance will be appreciated. I'ts on a local vps at the moment, however I can assign it a public IP.
Thanks in advance! Ash