Trigger active class of parent link when on child link page - javascript

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');

Related

Add class to active menu items with internal anchors

I have a page with a list of menu items consisting of internal anchors. I'm trying to add an .active class to the selected item. It seems to work on load but when clicking a new item in that same page it doesn't.
When clicking a new menu item, I would like to remove all other active classes and add this class to the clicked item.
Sounds pretty simple, but I can't make it work.
I created this Fiddle, but it doesn't show the issue correctly, since I can't add hashes to the url.
However, maybe someone can point me in the right direction.
JS:
function setActiveLinks() {
var current = location.pathname;
$('.bs-docs-sidenav li a').each(function() {
var $this = $(this);
// Get hash value
var $hash = location.href.substr(location.href.indexOf('#') + 1);
if ($this.attr('href') == '#' + $hash) {
$this.parent().addClass('active');
}
})
}
setActiveLinks();
$('#leftmenu li a').click(function() {
$('#leftmenu li').removeClass('active');
setActiveLinks();
});
HTML:
<ul class="nav bs-docs-sidenav">
<li>
Download
</li>
<li class="active">
What's included
<ul class="nav">
<li class="active">Precompiled</li>
<li>Source code</li>
</ul>
</li>
<li>
Compiling CSS and JavaScript
<ul class="nav">
<li>Installing Grunt</li>
<li>Available Grunt commands</li>
<li>Troubleshooting</li>
</ul>
</li>
</ul>
Thanks. :-)
You have wrong selector to bind click event on anchor element. also you don't need to call setActiveLinks() function(which sets class based on href) here.
You can use context of clicked anchor element to traverse to parent li and add class active in it:
var $navLIs = $('.nav li')
$navLIs.find('a').click(function() {
$navLIs.removeClass('active');
$(this).parent().addClass('active');
});
Working Demo

GET Basename of URL then put active class to navbar

Example Link: http://localhost/test/page.php
I have a JavaScript code that will put an active class to a navbar if the url of that href ==== current_url.
Current JavaScript (Only puts active class to sidebar)
<script type="text/javascript">
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('sub-menu active');
$(this).parent().closest("li").addClass('active');
$(this).parent().parent().closest("li").addClass('active');
}
});
});
</script>
I want to make it work also if the link has a page.php?success. There will also be an active class as long as the page.php is there regardless of what is after the ?.
I've tried the following script below to extract the basename but now it doesn't work at all, pages with or without ?.
Tried script (Supposed to put active class to sidebar even if the url has page.php?success in it.
<script type="text/javascript">
jQuery(function($) {
var patharray = window.location.pathname.split( '/' );
var reallink = patharray[2];
$('ul a').each(function() {
if (this.href === reallink) {
$(this).addClass('sub-menu active');
$(this).parent().closest("li").addClass('active');
$(this).parent().parent().closest("li").addClass('active');
}
});
});
</script>
With the example link above. The script returns page.php And the href's inside the navbar are just page1.php, page2.php etc... So I know it should work since the retrieved reallink is equal to the href of the navbar.
My sidebar
<li class="sub-menu"> // Sidebar with no submenu
<a class="" href="page1.php">
<i class="icon-calendar"></i>
<span>This is page 1</span>
</a>
</li>
<li class="sub-menu"> // Sidebar with a submenu
<a href="javascript:;" class="">
<i class="icon-group"></i>
<span>This has sub pages</span>
<span class="arrow"></span>
</a>
<ul class="sub">
<li><a class="" href="page2.php">This is page 2</a></li>
<li><a class="" href="page3.php">This is page 3</a></li>
</ul>
</li>
So the first JavaScript puts an active class both to the parent and the child if the href = url is met. But with the 2nd script nothing works.
I guess changing this line in the First script will make it work
var path = window.location.href.split( '?' )[0];

How to add active class to navigation items after the page url has changed

How can I achieve having a navigation menu automatically detect where to append the class of active the following structure I have is...
<ul class="navigation-list">
<li>Home</li>
<li>How it works</li>
<li>Hire your...</li>
<li>Pricing</li>
<li>Themes</li>
<li>Features</li>
<li>Why us</li>
<li>Blog</li>
</ul>
As you can see the Site is still under construction what I want to do is when you first visit the site the Home link will get a class of active like...
<li>Home</li>
and then when you click... let's say how it works you would then be taken over to the how it works page and the nav would remove active from home and append it to how it works like...
<li>How it works</li>
The $url parameter/tag outputs my url like http://www.example.com
I have already tried this but it will not work...
$(".navigation-list li a").each(function()
{
if (this.href.search(location.href) != -1)
{
$(this).addClass("active");
}
});
I have now tried the following and it worked...
$(function(){
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$");
$('.navigation-list li a').each(function(){
if(urlRegExp.test(this.href.replace(/\/$/,''))){
$(this).addClass('active');
}
});
});
although when I use it, When i'm at //mysite.org all the links in the navigation become active and then when i go to //mysite.org/blog/ it only activates the blog nav item

How to dynamically add a class to li item and change its background color using javascript and css

Here I have a list, what I want to do is I need to change the list ( li ) background color to different one after click on a specific list item. the thing is once it click on the link page will be redirected and refresh. please can me suggest a solution for to get this done?
<div id="main-menu">
<ul id="main-menu-list">
<li id="menu-home">Home</li>
<li id="menu-profile">My Profile</li>
<li id="menu-dashboard">My Dashboard</li>
<li id="menu-search">Search</li>
</ul>
</div>
what i did for this :
Java Script :
var make_button_active = function()
{
//Get item siblings
var siblings =($(this).siblings());
//Remove active class on all buttons
siblings.each(function (index)
{
$(this).removeClass('active');
}
)
//Add the clicked button class
$(this).addClass('active');
}
//Attach events to menu
$(document).ready(
function()
{
$("#main-menu li").click(make_button_active);
}
)
CSS :
#main-menu-list li.active {
background: #0040FF;
}
It's a little difficult to tell exactly what you want to do, but here's some quick and dirty (and untested) code:
/// when we click on an `a` tag inside the `#main-menu-list`...
$('#main-menu-list').on('click', 'a', function(e) {
// stop the link from firing
e.preventDefault();
e.stopPropagation();
// change the list item's background to green
$(this).closest('li').addClass('myClassName').css('background-color', 'green');
// do anything else, e.g. load in pages via ajax...
});
You could use CSS to apply the green background color, instead of jQuery:
.myClassName { background-color: green; }
This will stop the page from navigating, and I don't know if that's your intention. If you want to check the currently-loaded page against the menu to find the current item, you could do this (on page load) instead:
var currentPage = window.location.pathname;
$('#main-menu-list').find('a[href^="' + currentPage + '"]').closest('li').addClass('active');
EDIT:
Your amended Javascript code can be simplified to the following:
$('#main-menu li').on('click', 'a', function (e) {
e.preventDefault();
e.stopPropagation();
// only do the following if the clicked link isn't already active
if(!$(this).closest('li').hasClass('active')) {
$(this).closest('ul').find('.active').removeClass('active');
$(this).closest('li').addClass('active');
// load in your content via ajax, etc.
}
});
JSFiddle example
For each page you can add a class to the current list item that has "where the user is"..
CSS:
.selectedItem{
background-color: orange;//whatever color your want for the selected tab..
}
Then for each of your pages,
say you're in Dashboard.html
your menu code will look like:
<div id="main-menu">
<ul id="main-menu-list">
<li id="menu-home">Home</li>
<li id="menu-profile">My Profile</li>
<li id="menu-dashboard" class="selectedItem">My Dashboard</li>
<li id="menu-search">Search</li>
</ul>
</div>
in profile.html:
<div id="main-menu">
<ul id="main-menu-list">
<li id="menu-home">Home</li>
<li id="menu-profile" class="selectedItem">My Profile</li>
<li id="menu-dashboard">My Dashboard</li>
<li id="menu-search">Search</li>
</ul>
</div>
and so on..
You need to change the background color when the document is loaded (i.e. in document.ready).
Then you need a mechanism to connect the currently loaded page to one of your list items.
$(document).ready(function(){
//get the url from the current location or in some other way that suits your solution
//perhaps use window.location.pathname
var moduleId = "dashboard" // hardcoded to dashboard to make the point :);
$("#menu-"+moduleId).css("background-color", "#ccc");
});
http://jsfiddle.net/9JaVn/1/

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