Reputation: 157
I am trying to make my website's menu in one file only and just include it in the rest of the .html pages. I am copy and pasting the menu each time I make a new page because I want the tab that is active to be highlighted for each different page. This is the reason why I can't make one file only for every page, and I have no idea how can I make it work to set the tab active in each different page.
This is the code I am copy-pasting in each page.
<!-- BEGIN MENU -->
<section id="menu-area">
<nav class="navbar navbar-default" role="navigation">
<div class="container">
<div id="navbar" class="navbar-collapse collapse">
<ul id="top-menu" class="nav navbar-nav navbar-right main-nav">
<li><a href="index.php">Home</a></li>
<li><a href="404.php">Downloads</a></li>
<li><a href="404.php">Media</a></li>
<li class="dropdown"><a href="#" class="dropdown-toggle"
data-toggle="dropdown">Research <span
class="fa fa-angle-down"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="404.php">D3</a></li>
</ul></li>
<li><a href="team.php">Team</a></li>
<li class="active"><a href="contact.php">Contact</a></li>
</ul>
</div>
<!--/.nav-collapse -->
<a href="#" id="search-icon"> <i class="fa fa-search"> </i>
</a>
</div>
</nav>
</section>
<!-- END MENU -->
In this case the contact tab is highlighted:
<li class="active"><a href="contact.php">Contact</a></li>
If the case is that the home page is active, then I would need to do this:
<li class="active"><a href="index.php">Home</a></li>
I hope I made myself clear, my English is terrible. I appreciate any idea, I am really new at web development.
Upvotes: 1
Views: 520
Reputation: 71
Using D3
<script>
var pgUrl = window.location.href.substr(window.location.href.lastIndexOf('/') + 1);
d3.select("#navbar").selectAll("a").each(function(d){
if(d.tecode here == pgUrl )
d.attr("class","active");
});
</script>
Upvotes: 1
Reputation: 63
I think this way more useful:
$(function(){
var pgUrl = window.location.href.substr(window.location.href.lastIndexOf('/') + 1);
$("#nav ul li a[href='"+ pgUrl +"']").addClass('active');
});
Upvotes: 1
Reputation: 7504
One thing you can do is to read the URL and on base of that you add the active class
to that link in your menu.
$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
$("#nav ul li a").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
$(this).addClass("active");
})
});
Upvotes: 2