I'm new to the twitter bootstrap. Using there navigation menus . I'm trying to set active class to selected menu. my menu is -
<div class="nav-collapse">
<ul class="nav">
<li id="home" class="active"><a href="~/Home/Index">Home</a></li>
<li><a href="#">Project</a></li>
<li><a href="#">Customer</a></li>
<li><a href="#">Staff</a></li>
<li id="broker"><a href="~/Home/Broker">Broker</a></li>
<li><a href="#">Sale</a></li>
</ul>
</div>
I tried following thing after googling on this that i have to set active class on each page from menu like as--
<script>
$(document).ready(function () {
$('#home').addClass('active');
});
</script>
but problem for above is that i set home menu selected by default. Then it always get selected. Is there any other way to do this ? , or which i can generalize and keep my js in layout file itself?
After executing application my menu looks -
after clicking on other menu item i get following result-
And i added following scripts on Index view and Broker view ---
<script>
$(document).ready(function () {
$('#home').addClass('active');
});
</script>
<script>
$(document).ready(function () {
$('#broker').addClass('active');
});
</script>
respectively.
example:
For single-page sites where the menu items simply jump down to other sections of the page, this simple solution works for me:
I am using Flask Bootstrap. My solution is a little bit simpler because my template already receives the option or choice as a parameter from Flask.
First line, js code gets the element. So, you should identify each of the elements with a id. I'll show an example below. Second line, you add the class active. You can see html ids below.
You can use this
JavaScript\jQuery
code:It'll set the
<a>
's parent<li>
and the<li>
's parent<ul>
as active.A simple solution that works!
Original source:
Bootstrap add active class to li
You could add a diffrent class onto the BODY tag on each page e.g. on the homepage you could have this:
Then this css:
The NAV element:
#Alternatively you could place a class on the BODY on each page and then grab that via jQuery and add the .active class to the correct nav item based on that tag.