So I'm trying to set "active" class on a list item from bootstrap menu. I have my menu file separate from all other html files so I don't have to maintain multiple menu code across my site. I'm using jquery to load the menu file like so
$(function () {
$("#MainMenu").load("menu.html");
});
Inside the menu file I have this code I got from another answer on this site. While it does work it won't load the html files and stays on the index.html
$("#myNavbar li").click(function (e) {
e.preventDefault();
$('#myNavbar li').removeClass('active');
$(this).addClass('active');
});
If I remove e.preventDefault(); and change function (e) to function () it will load the html files but it will not set class active
I've tried putting the code into the main html files and it doesn't work at all. I've tried putting it into my seperate JS file for all of my custom js and it doesn't work. By adding the code to the top of the menu.html inside script tags has been the only way for me to get any kind of result.
Any help would be much appreciated.
EDIT: nav menu html code
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">brand</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="#">About</a></li>
<li><a href="resume.html">Resume</a></li>
<li><a href="#">Work</a></li>
<li><a href="#">Companies</a></li>
<li><a href="#">Blog</a></li>
</ul>
</div>
</div>
</nav>
I figured out the answer, well, work around. This way I think is better anyway and also better code management. I had it backwards. I was trying to insert the menu and footers into every page. What I should be doing, and am now doing, is injecting the links into the index page that contains the menu and footer. After changing around some code it works perfect. For the those of you who may have this same question, or problem, the JS code for the menu is
The js code for loading the links into the page (also loads the about.html when the page is loaded) is
I just duplicated the same code for the footer links and attached "f" to the end of each ID for example
#workis#workffor the footer.I hope this is clear enough for anyone who is searching for the same solution.