Bootstrap. Keep active class on new page - javascript

I have faced a problem with adding "active" class to my tabs.
I know how to add active class to tab when i click on it. But i don't know how to save active class on tab after page reload.
Part of my jsp code
<div class="row top-buffer">
<div class="col-md-10 col-md-offset-1 products">
<ul class="nav nav-pills cat-nav">
<c:forEach items="${catList}" var="category">
<li role="presentation" >
<a href="/show-category?id=${category.id}" >${category.name}</a>
<ul class="dropdownn">
<c:forEach items="${category.childCategories}" var="childCat">
<li>${childCat.name} </li>
</c:forEach>
</ul>
</li>
</c:forEach>
<li role="presentation" class="pull-right">All </li>
</ul>
</div>
</div>
Script for adding active class
$(document).ready(function () {
$('.cat-nav li a').click(function(e) {
$('.cat-nav li').removeClass('active');
var $parent = $(this).parent();
if (!$parent.hasClass('active')) {
$parent.addClass('active');
}
});
});
When i click on link it send me to another page, but that another page has no active class. So how can i "save" or "hold" active class and put in in new page.

Inside your click handler you are adding and removing the 'active' class on the <li> element. In bootstrap the 'active' class is applied to the <a> element instead. With a small adjustment to your code this works:
$('.cat-nav li a').click(function() {
$('.cat-nav li a').removeClass('active');
$(this).addClass("active");
});
Link to example in codepen:
http://codepen.io/johnwilson/pen/akVgxq

Finally i have solved it !
$(document).ready(function () {
var id = getParameterByName('id');
$('.cat-nav li[role="presentation"]').each(function() {
var id2 = $(this).attr("id");
if(id == id2){
$(this).addClass('active');
}
});
});
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
localStorage.setItem(name, results[2].replace(/\+/g, " "));
var result = localStorage.getItem("id");
return result;
}
<div class="row top-buffer">
<div class="col-md-10 col-md-offset-1 products">
<ul class="nav nav-pills cat-nav">
<c:forEach items="${catList}" var="category">
<li role="presentation" id="${category.id}">
<a href="/show-category?id=${category.id}" >${category.name}</a>
<ul class="dropdownn">
<c:forEach items="${category.childCategories}" var="childCat">
<li>${childCat.name} </li>
</c:forEach>
</ul>
</li>
</c:forEach>
<li role="presentation" class="pull-right" id="0">All </li>
</ul>
</div>
</div>

Related

Get a parent class jquery

I want to get the ancetor of the li that have active class to target his son (the button) class an make a collapse by area-expanded= true in it.
This is the html:
<li class="nav-item">
<button class="nav-link" type="button" data-toggle="collapse" data-target="#nav-collapse-2" aria-controls="nav-collapse-2" aria-expanded="true">Typographies</button>
<div class="nav-collapse collapse show" id="nav-collapse-2" style="">
<div class="nav-collapse-inner">
<ul class="nav-submenu">
<li class="nav-submenu-item">
<a class="nav-submenu-link active" href="sg-typo-familles.html">Les familles</a>
</li>
<li class="nav-submenu-item">
<a class="nav-submenu-link" href="sg-typo-hierarchisation.html">Hiérarchisation</a>
</li>
</ul>
</div>
</div>
</li>
this is some js :
var get_url = function (){
$(".navbar-nav--left .nav-link, .nav-submenu .nav-submenu-link").each(function(){
var $this = $(this);
if($this.attr('href') == window.location.href.substr(window.location.href.lastIndexOf('/') + 1)){
// var regex = /\/\/.*\/(.*)\//g;
// var match = regex.exec(window.location.href);
// console.log("eeeeeee : ",match )
$this.addClass('active');
// var collapsed = $(".nav-item *");
collapsed = $(this).closest(".nav-item")[0];
}
});
};
I'm stuck in this piece of code :(
I didn't understand well your question, but in order to get the parentElement of an element with a class .active here is how:
let myElement = document.getElementByClassName("active")[0];
let brotherButton = myElement.parentNode.querySelectorAll("a")[0];
Above we've got myElement which has the class .active, then thru his parent we selected his brother anchor tag.
Hope this help.

How to add active class on specific li on user click after page load using JavaScript

I have a menu with certain items and I want when a user clicks on any li than only its class becomes an active class. I have menu items like the following:
$(document).ready(function () {
$(function () {
var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
alert(pgurl);
$(".nav li a").each(function () {
if ($(this).attr("href") == pgurl || $(this).attr("href") == '') {
$(this).addClass("active");
}
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-9">
<nav class="nav-holder">
<div class="nav-footer">
<ul class="nav" id="navclk">
<li class="active">
Home
</li>
<li class="">
About
</li>
<li class="">
Car Rentals
</li>
<li class="">
Wedding Cars
</li>
<li class="">
Tempo Travellers
</li>
<li class="">
Tour Package
</li>
<li class="">
Coach
</li>
<li class="has-submenu">
Places
<ul class="submenu">
<li>Bhubaneswar</li>
<li>Puri</li>
<li>Konark</li>
<li>Chilika</li>
<li>Gopalpur</li>
<li>Cuttack</li>
<li>Bhitar Kanika</li>
<li>Daringbadi</li>
<li>Jajpur</li>
</ul>
</li>
<li>Contact</li>
</ul>
</div>
</nav>
</div>
It's not working with the drop-down menus while working perfectly with all other menus not having drop-down items. How can I change the code that it works too with menu items having a drop-down list of items? I am also using update panel on my page.
This could be done by the following code
CSS
.active {
/* your active CSS */
}
html
<ul>
<li onclick="activeMe(this)">1</li>
<li onclick="activeMe(this)">2</li>
<li onclick="activeMe(this)">3</li>
<li onclick="activeMe(this)">4</li>
</ul>
JavaScript
function activeMe(li) {
console.log(li.setAttribute("class", "active"));
}
``
Correct Answer!
<!--Menu Active-->
<script type="text/javascript">
$(document).ready(function () {
$('.nav li').removeClass('active');
$(function () {
var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$(".nav li a").each(function () {
if ($(this).attr("href") == pgurl) {
$(this).closest('li').addClass("active");
}
})
});
});
</script>
<!--Menu Active-->

get current URL path and assign 'active' and add class from foreach laravel

i want like this why class alert alert-success cannot add to tag a href?
<ul class="nav nav-pills" id="nav">
#foreach($menu as $d)
<li role="presentation"><a class="text-capitalize " href="{!! $d->name !!}">{!! $d->name !!}</a></li>
#endforeach
</ul>
<script type="text/javascript">
$(document).ready(function() {
// get current URL path and assign 'active' class
var pathname = window.location.pathname;
$('.nav > li > a[href="'+pathname+'"]').parent().addClass('alert alert-success');
})
</script>
Try using the following
$('.nav > li > a[href*="'+pathname+'"]').parent().addClass('alert alert-success');

I want to add some classes to my nav

i use .selected for topnav and .active for sub navs
<div class="nav-collapse collapse navbar-collapse navbar-responsive-collapse">
<ul class="nav navbar-nav uppercase col-md-10">
<li class="dropdown dropdown-fw open selected">
<i class="icon-home"></i> Dashboard
<ul class="dropdown-menu dropdown-menu-fw">
<li class="active">Dashboard</li>
</ul>
</li>
<li class="dropdown dropdown-fw">
<i class="icon-puzzle"></i>example
<ul class="dropdown-menu dropdown-menu-fw">
<li class="disabled">example1</li>
<li>example2</li>
<li class="disabled">Sexample3</li>
<li>example4</li>
</ul>
</li>
</ul>
what i want is when i click and redirect to an other page i want javascript to detect the url of the page and active the links inside my navbar that contains the same href value as the url + add selected class to the parent of .dropdown-menu-fw
var url = window.location;
console.log(url);
$('.dropdown-menu-fw li a[href="'+ url +'"]').parent().addClass('active');
$('.dropdown-menu-fw li a').filter(function() {
return this.href == url;
}).parent().addClass('active');
Maybe you meant
var url = window.location.href; instead of .location?
That way the whole URL is retrieved.
.location retrieves an object.
This is working for me
$(document).ready(function(){
var url = window.location.href;
$('.dropdown-menu-fw li').removeClass('active');
$('.dropdown-menu-fw li a').filter(function() {
return this.href == url;
}).parent().addClass('active');
$('.dropdown-fw').removeClass('selected open');
$('.dropdown-menu-fw li a[href="'+ url+'"]').closest(".dropdown-fw").addClass('open selected');
// $('.dropdown-menu-fw li a').parentsUntil(".dropdown-fw").addClass('open');
});

how to set active class to nav menu from twitter bootstrap

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");
});

Categories