how to set active class to nav menu from twitter bootstrap - javascript

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">Home</li>
<li>Project</li>
<li>Customer</li>
<li>Staff</li>
<li id="broker">Broker</li>
<li>Sale</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.

You can use this JavaScript\jQuery code:
// Sets active link in Bootstrap menu
// Add this code in a central place used\shared by all pages
// like your _Layout.cshtml in ASP.NET MVC for example
$('a[href="' + this.location.pathname + '"]').parents('li,ul').addClass('active');
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

it is a workaround. try
<div class="nav-collapse">
<ul class="nav">
<li id="home" class="active">Home</li>
<li>Project</li>
<li>Customer</li>
<li>Staff</li>
<li id="demo">Broker</li>
<li id='sale'>Sale</li>
</ul>
</div>
and on each page js add
$(document).ready(function () {
$(".nav li").removeClass("active");//this will remove the active class from
//previously active menu item
$('#home').addClass('active');
//for demo
//$('#demo').addClass('active');
//for sale
//$('#sale').addClass('active');
});

I had the same problem... solved it by adding the code shown below to the Into "$(document).ready" part of my "functions.js" file which is included in every page footer. It's pretty simple. It gets the full current URL of the displayed page and compares it to the full anchor href URL. If they are the same, set anchor (li) parent as active. And do this only if anchor href value is not "#", then the bootstrap will solve it.
$(document).ready(function () {
$(function(){
var current_page_URL = location.href;
$( "a" ).each(function() {
if ($(this).attr("href") !== "#") {
var target_URL = $(this).prop("href");
if (target_URL == current_page_URL) {
$('nav a').parents('li, ul').removeClass('active');
$(this).parent('li').addClass('active');
return false;
}
}
}); }); });

For single-page sites where the menu items simply jump down to other sections of the page, this simple solution works for me:
$('.nav li').on('click', function(){
$('.nav li').removeClass('active');
$(this).addClass('active');
});

You could add a diffrent class onto the BODY tag on each page e.g. on the homepage you could have this:
<body class="nav-1-on">
Then this css:
.nav-1-on .nav-1 a, .nav-2-on .nav-2 a, .nav-3-on .nav-3 a, .nav-4-on .nav-4 a {
// set your styles here
}
The NAV element:
<ul>
<li class="nav-1">Home</li>
<li class="nav-2">Services</li>
<li class="nav-3">About</li>
<li class="nav-4">Contact</li>
</ul>
#
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.

<div class="nav-collapse">
<ul class="nav">
<li class="home">Home</li>
<li class="Project">Project</li>
<li class="Customer">Customer</li>
<li class="Staff">Staff</li>
<li class="Broker">Broker</li>
<li class="Sale">Sale</li>
</ul>
</div>
then for each page you add this:
//home
$(document).ready(function () {
$('.home').addClass('active');
});
//Project page
$(document).ready(function () {
$('.Project').addClass('active');
});
//Customer page
$(document).ready(function () {
$('.Customer').addClass('active');
});
//staff page
$(document).ready(function () {
$('.Staff').addClass('active');
});

<div class="nav-collapse">
<ul class="nav">
<li class="home">Home</li>
<li class="Project">Project</li>
<li class="Customer">Customer</li>
<li class="Staff">Staff</li>
<li class="Broker">Broker</li>
<li class="Sale">Sale</li>
</ul>
</div>
$('ul.nav>li.home>a').click(); // first. same to all the other options changing the li class name

For single page sites, the following is what I used. It not only sets the active element based on what's been clicked but it also checks for a hash value within the URL location on initial page load.
$(document).ready(function () {
var removeActive = function() {
$( "nav a" ).parents( "li, ul" ).removeClass("active");
};
$( ".nav li" ).click(function() {
removeActive();
$(this).addClass( "active" );
});
removeActive();
$( "a[href='" + location.hash + "']" ).parent( "li" ).addClass( "active" );
});

For those using Codeigniter, add this below your sidebar menu,
<script>
$(document).ready(function () {
$(".nav li").removeClass("active");
var currentUrl = "<?php echo current_url(); ?>";
$('a[href="' + currentUrl + '"]').parents('li,ul').addClass('active');
});
</script>

(function (window) {
bs3Utils = {}
bs3Utils.nav = {
activeTab: function (tabId) {
/// <summary>
/// 设置需要展现的tab
/// </summary>
/// <param name="tabId"></param>
$('.nav-tabs a[href="#' + tabId + '"]').tab('show');
}
}
window.bs3Utils = bs3Utils;
})(window);
example:
var _actvieTab = _type == '0' ? 'portlet_tab2_1' : 'portlet_tab2_2';
bs3Utils.nav.activeTab(_actvieTab);
<ul class="nav nav-tabs">
<li class="active">
箱-单灯节点
</li>
<li>
箱-灯组节点
</li>
</ul>

$( ".nav li" ).click(function() {
$('.nav li').removeClass('active');
$(this).addClass('active');
});
check this out.

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.
var choice = document.getElementById("{{ item_kind }}");
choice.className += "active";
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.
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a id="speed" href="{{ url_for('list_gold_per_item',item_kind='speed',level='2') }}">
<h2>Speed</h2>
</a>
</li>
<li>
<a id="life" href="{{ url_for('list_gold_per_item',item_kind='life',level='3') }}">
<h2>Life</h2>
</a>
</li>
</ul>
</div>

I just added a custom class to the ul section named target-active
<ul class="nav navbar-nav target-active">
<li>HOME</li>
<li>FIND A TRUCK</li>
<li>OUR SERVICES</li>
<li>ABOUT US</li>
</ul>
If each li tags click get a new page from different place or same place, no need to add jquery removeClass function.
Add simple one line jquery code to each page to get your desired result
1st link page
$(function(){
$(".target-active").find("[href='/']").parent().addClass("active");
});
2nd link page
$(function(){
$(".target-active").find("[href=find-truck]").parent().addClass("active");
});
3rd link page
$(function(){
$(".target-active").find("[href=our-service]").parent().addClass("active");
});
4th link page
$(function(){
$(".target-active").find("[href=about-us]").parent().addClass("active");
});

Related

How to highlight active menu of a dropdown menu of bootstrap using jquery?

I want menu item to be highlighted when an item is selected in the drop down. I tried following code. Code is working if I prevent default behavior of a which I don't want, So I tried using local storage but it is not working, only page refreshes and default Home item of menu is highlighted.
Menu
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li class="dropdown">
Fire & Water <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>Water Damage</li>
<li>Fire Damage</li>
<li>Storm Damage</li>
<li>Commercial Restoration</li>
</ul>
</li>
<li class="dropdown">
Mold <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>Mold Remediation</li>
<li>What is Black Mold?</li>
<li>Mold "Removal" vs Remediation</li>
<li>Commercial Mold Remediation</li>
</ul>
</li>
</ul>
This is Working
$(document).ready(function(){
$(".dropdown-menu li a").click(function(e){
e.preventDefault();
var hrefs = $(this).attr('href');
alert("hrefs : " + hrefs);
$("li").removeClass('active');
$('a[href="' + hrefs + '"]').parents('li').addClass('active');
});
});
This is not working
$(document).ready(function(){
$(".dropdown-menu li a").click(function(){
var hrefs = $(this).attr('href');
alert("hrefs : " + hrefs);
localStorage.setItem('activeTab', hrefs);
var activeTab = localStorage.getItem('activeTab');
$("li").removeClass('active');
alert("activeTab : " + activeTab);
$('a[href="' + activeTab + '"]').parents('li').addClass('active');
});
});
I think, you have to apply active class on page load event not in click event. your code should be something like as below
$(document).ready(function(){
// activate left navigation based on current link
var current_url = window.location;
$('.dropdown-menu li a').filter(function () {
return this.href == current_url;
}).last().parents('li').addClass('active');
});
On every page load, you have to filter out link of current page from your navigation bar and then apply class active in parent. I have posted code for your explanation purpose you have to modify as per your HTML code structure.
Hope, this will work :)

Trigger active class of parent link when on child link page

I have the javascript code below to put my parent menu item to class active when I'm on the page for example https://stackoverflow.com/questions/ it works. But I also wanna put the parent menu item to class active when I'm at the subpages/child menu item like https://stackoverflow.com/questions/ask/, may I know how to do that?
Example I'm at this page https://stackoverflow.com/questions/ask/, how to I get the URL like this https://stackoverflow.com/questions/, without the /ask so that I can have the parent menu item (question) to be in active class when I'm at the child page of question which is (ask).
The code below only works if I'm at https://stackoverflow.com/questions/, but if I'm at the child page https://stackoverflow.com/questions/ask/, parent link (https://stackoverflow.com/questions/) doesn't change to active class.
<ul class="nav navbar-nav">
<li><h5>Home</h5></li>
<li class="dropdown">
<h5>Online<span class="caret"></span></h5>
<ul class="dropdown-menu" role="menu">
<li>History</li>
<li>Science</li>
<li>Mathematics</li>
<li>English</li>
</ul>
</li>
</ul>
<script type="text/javascript">
var url = window.parent.location.href;
$('ul.nav a[href="'+ url +'"]').parent().addClass('active');
$('ul.nav a').filter(function() {
return this.href == url;
}).parent().addClass('active');
</script>
You can use parents() to match the parent and all ancestors. Give it a selector argument to restrict to just the li tags.
$('ul.nav a').filter(function() {
return this.href == url;
}).parents('li').addClass('active');

Twitter Bootstrap with PLAY framework setting nav bar <li> elements to active

Hi I have a navbar in my home.scala.html as follows-
<ul class="nav nav-justified">
<li>#Messages("views.main.apps")</li>
<li >#Messages("views.main.activity")</li>
<li>#Messages("views.main.devices")</li>
<li>#Messages("views.main.account")</li>
<li id="logout">#Messages("views.main.logout")</li>
</ul>
I am trying to set active class on click as follows-
<script>
$(document).ready(function () {
$('ul.nav > li').click(function (e) {
$('ul.nav > li').removeClass('active');
$(this).addClass('active');
});
});
</script>
However on running the application only the li elements which have href="#" get set as active ,the other li elements remain inactive on click even though the page is redirected to the link of the tag.
Any help would be appreciated.
Thanks
Edit:The structure of the main.scala.html is
<html>
<head></head><body>
<ul class="nav nav-justified">
<li>#Messages("views.main.apps")</li>
<li >#Messages("views.main.activity")</li>
<li>#Messages("views.main.devices")</li>
<li>#Messages("views.main.account")</li>
<li id="logout">#Messages("views.main.logout")</li>
</ul>
</div>
</nav>
<div id="showsspData">
#content
</div>
</div>
</body>
</html>
Then the apps.scala.html will be as-
#main("string to pass"){
//html content for page
}
You need to use e.preventDefault() to prevent default action of the anchor and target .click() handler on the anchors instead:
$(document).ready(function () {
$('ul.nav > li a').click(function (e) {
e.preventDefault();
$('ul.nav > li').removeClass('active');
$(this).closest('li').addClass('active');
});
});

onclick open sub menu, on click close sub menu?

On this page http://kimcolemanprojects.com/ I need to have a drop down menu that opens on click and closes again on click of same anchor. Like it works on this site http://angela-moore.co.uk/
This is my html for the menu so far:
<div class="left" id="nav">
<ul id="menu">
<li id="light">
Lighting + Video
<ul style="display: none;">
<li>Django Django</li>
<li>Suntrap</li>
</ul>
</li>
<li id="photo">
Photograms
</li>
<li id="about">
<a class="active" href="about.html">About</a>
</li></ul>
</div><!--end nav-->
As you can see I only need it to work within one list item. I need help writing the Javascript for this.
So when on index page the user can see three links lighting + video, Photograms, About. When user clicks on lighting + video a sub menu opens beneath with more links. Then it will close again if the user clicks again on lighting + video. The same can happen with each of the initial three links on the index page.
Quite Simple..
<script src="jquery.js"></script>
<div id="navigation">
<p>Menu</p>
<ul id="menu">
<li>Menu 1<ul>
<li>lol</li><li>lol2</li><li>lol</li><li>lol2</li>
</ul></li>
<li>Menu 2<ul>
<li>lol</li><li>lol2</li><li>lol</li><li>lol2</li>
</ul></li>
<li>Menu 3<ul>
<li>lol</li><li>lol2</li><li>lol</li><li>lol2</li>
</ul></li>
<li>Menu 4<ul>
<li>lol</li><li>lol2</li><li>lol</li><li>lol2</li>
</ul></li>
This will be your HTML container etc, under this you will need your javascript to control that hiding and changing!! You can add some styling also if you feel artistic!
<script>
var showMenuText = $('#toggle').text();
var hideMenuText = 'Close';
$('#navigation ul').hide();
$('#navigation ul a.active+ul').show();
hideMenu = function() {
$('#navigation ul#menu').hide();
$('#navigation').removeClass('open');
$('#toggle').text(showMenuText);
}
$('#toggle').click(function(event){
event.stopPropagation(); event.preventDefault();
$('#navigation ul#menu').toggle();
$('#navigation').toggleClass('open');
var toggleText = $('#toggle').text();
(toggleText == showMenuText) ? $(this).text(hideMenuText) : $(this).text(showMenuText);
});
$('ul#menu > li > a').click(function(event){
$this = $(this);
if( $this.hasClass('page') ) parent.location = $this.attr('href');
if( $this.hasClass('home') ) { parent.location = '/'; }
event.preventDefault(); event.stopPropagation();
if( $this.hasClass('active') ) var justclosed = true;
$('a.active').removeClass('active').next('ul').hide();
if(!justclosed) $this.addClass('active').next('ul').show();
});
</script>
This is a simple HTML Example and you can execute it how you like.

css class active after page reload

i'm having some trouble.
I'm doing an asp.net mvc3 application and i downloaded some css menu, the thing is i want to keep the menu active after menu tab its clicked and only change when another one is clicked.
here's the code of the menu on _Layout.cshtml
<nav>
<div class="cssmenu">
<ul>
<li class='active'><span>#Html.ActionLink("Início", "Index", "Home")</span></li>
<li><span>#Html.ActionLink("Tarefas Contabilidade", "SelectEmpresa", "Empresa")</span></li>
<li><a href='#'><span>Clientes</span></a>
<ul>
<li><span>#Html.ActionLink("Listar clientes", "ListarEmpresas", "Empresa")</span></li>
</ul>
</li>
<li><a href='#'><span>Balancetes</span></a>
<ul>
<li><span>#Html.ActionLink("Listar registos", "ListaBalancetesPorSalaoMes", "Balancete")</span></li>
</ul>
</li>
<li><span>#Html.ActionLink("Sobre", "About", "Home")</span></li>
</ul>
</div>
</nav>
and i have this script:
<script type="text/javascript">
$("li").click(function () {
$("li").removeClass("active");
$(this).addClass("active");
});
</script>
the first tab that i put there class= "active" works, but the script doesn't seem to work when i click another menu tab, it only shows the first one active
a little help please :)
UPDATED
This is the rendered html:
<nav>
<div class="cssmenu">
<ul>
<li><span>Início</span></li>
<li><span>Tarefas Contabilidade</span></li>
<li><a href='#'><span>Clientes</span></a>
<ul>
<li><span>Listar clientes</span></li>
<li><span>Listar salões</span></li>
<li><span>Gerir empregados</span></li>
<li><span>Novo cliente</span></li>
<li><span>Novo salão</span></li>
</ul>
</li>
<li><a href='#'><span>Balancetes</span></a>
<ul>
<li><span>Listar registos</span></li>
<li><span>Upload novo balancete</span></li>
<li><span>Mapa Resultados/Gráfico</span></li>
<li><span>Mapas Contabilidade/Gestão</span></li>
<li><span>Análise Rentabilidade</span></li>
<li><span>Alterar taxas</span></li>
</ul>
</li>
<li><span>Sobre</span></li>
</ul>
</div>
</nav>
i dont know if i should put the javascript inside the div or something xD
Ty
You can use child selector which selects all direct child elements, Try the following:
$(document).ready(function(){
$(".cssmenu > ul > li").click(function () {
$(this).siblings().removeClass("active");
$(this).addClass("active");
});
})
If you want to select the li tags of the inner ul tags, you can try:
$(document).ready(function() {
$("ul:eq(1) > li").click(function() {
$('ul:eq(1) > li').removeClass("active");
$(this).addClass("active");
});
})
Can you try:
<script type="text/javascript">
$("li a").bind('click', function () {
$("li").removeClass("active");
$(this).addClass("active");
});
</script>
li items are not clickable, so you must bind the click event to a.
try
$("li").click(function (e) {
e.preventDefault();
$(this).siblings().removeClass("active").end().addClass("active");
});

Categories