Add active class to nav li depending on url? - javascript

I'm having some real hard time adding class active to the li that contains the current page the site is on. URL = http://polissagethibodeau.com/
Here is the relevant HTML
<nav class="nav">
<ul class="sf-menu">
<li id="home">
Home
</li>
<li>
About us
</li>
<li>
Services
<ul>
<li>
Car, Truck and Vans
</li>
<li>
Semi, Boats, RV and Busses
</li>
<li>
Airplanes and Helicopters
</li>
<li>
Aluminum and Plexiglass polishing</li>
</ul>
</li>
<li>
Photos
</li>
<li>
Contact Us
</li>
</ul>
</nav>
CSS I am trying to apply
.sf-menu > li.active > a {
background: #c2e078;
}
Here is the script I am trying to use to no success.
$(function() {
var path = window.location.pathname.substring(1);
$('.nav>li>a[href="' + path + '"]').parent().addClass('active');
});

YOU can do it by two or many way. Example project
Source LINK
1.----
$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
$("nav ul a").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
$(this).addClass("active");
})
});
2.----
here's the code if u want to use plain javascript
function setActive() {
aObj = document.getElementById('nav').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
aObj[i].className='active';
}
}
}
window.onload = setActive;
3.----
function setActive() {
$('#nav').find('a').each(function () {
//console.log(document.location.href)
if (document.location.href == "http://......" + $(this).attr('href')) {
$(this).parents("ul").removeClass("hidden-ul");
$(this).parents().addClass("active");
}
});
}
window.onload = setActive;

Use a if statement to check if it is in the url:
<script>
$(function() {
var path = window.location.pathname.substring(1);
if(window.location.href = path) {
$('.nav>li>a[href="' + path + '"]').parent().addClass('active');
}
});
</script>

Its because the HREF property of each of those links is going to be equal to a complete URL, not just file.php
You can get around this by using the $= operator which means (ends with)
Note in the DEMO I changed the var path assignment to just services.php so that it would work in the snippet.
Also, use the $(document).ready(function() { trigger to properly add a listener to an event
Note I realize that this example will cause all of the links to services.php to have the class active added to them. To get around this assign a custom class called navlink to each link in the navigation bar and then use
$('.navlink[href$="' + path + '"]:parent').addClass('active');
$(document).ready(function() {
//var path = window.location.pathname.substring(1);
var path = 'services.php#large';
$('a[href$="' + path + '"]:parent').addClass('active');
});
.active {
font-size: 1.75em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="nav">
<ul class="sf-menu">
<li id="home">
<a href="./" >Home</a>
</li>
<li>
About us
</li>
<li>
Services
<ul>
<li>
Car, Truck and Vans
</li>
<li>
Semi, Boats, RV and Busses
</li>
<li>
Airplanes and Helicopters
</li>
<li>
Aluminum and Plexiglass polishing</li>
</ul>
</li>
<li>
Photos
</li>
<li>
Contact Us
</li>
</ul>
</nav>

$(document).ready(function () {
// Get previously stored url
if (sessionStorage.getItem("active-class-url"))
{
strLastUrl = sessionStorage.getItem("active-class-url");
$('.nav > li >a[href="' + strLastUrl + '"]').parent().addClass('active');
}
});
$(document).on(".nav > li > a", "click", function () {
// Remove active class from all ancher tag
$(".nav > li > a").parent("li").removeClass('active');
// Add active class to currenly clicked acnher tag
$(this).parent("li").addClass('active')
// Store value of active calss url. So on page refresh you can get it
sessionStorage.setItem("active-class-url", $(this).attr("href"));
})

The problem is your selector.
Instead of this:
$(".nav > li > a")
Use this:
$(".nav > ul > li > a")
Also remove the . (dot) before your paths, and this will work:
$(document).ready(function() {
var pathname = window.location.pathname;
$(".nav > ul > li > a").each(function() {
var $this = $(this);
if ($this.attr("href") === pathname) {
$this.parent().addClass("active");
}
});
});
Test:

$(document).ready(function() {
var url = window.location.toString();
$('#home a').attr('href',url)
$('#home a').text(url)
$('ul.sf-menu a').filter(function() {
if (this.href != '') {
if (this.href == url) {
console.log(this.href)
console.log(url)
$(this).addClass('active');
}
}
});
});
.active {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="nav">
<ul class="sf-menu">
<li id="home">
Home
</li>
<li id="stacksnippets">
stacksnippets
</li>
</ul>
</nav>
try above method I hope it helps you.

Related

Setting an active menu item current URL with jQuery

I'm trying to add active class to current menu item. So far my HTML looks like this:
<ul id="navmenu" class="navigation">
<li >
Home
</li>
<li class="sub_navmenu">
About me
<ul>
<li>
Item 1
</li>
<li>
Item 1
</li>
<li>
Item 1
</li>
</ul>
</li>
<ul>
It would be nice to have active class on for example on item 1 and parent li element which is sub_navmenu.
My jQuery is like this:
$(function () {
setNavigacija();
});
function setNavigacija() {
var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);
$("#navmenu li a").each(function () {
var href = $(this).attr('href');
if (path.substring(0, href.length) === href) {
$(this).closest('li').addClass('active');
}
});
}
Fiddle link https://jsfiddle.net/41uLs8md/12/
Seems like a problem with your if (path.substring(0, href.length) === href) {
You can try something link this.
$(function () {
setNavigacija();
});
function setNavigacija() {
var path = window.location.href;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);
$("#navmenu li a").each(function () {
var href = $(this).attr('href');
if (path.indexOf(href) != -1) {
$(this).closest('li').addClass('active');
}
});
}
$(function () {
setNavigacija();
});
function setNavigacija() {
var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);
//$(".sub_navmenu ul li a").addClass('active');
$("#navmenu li a").each(function () {
var href = $(this).attr('href');
if (path.substring(0, href.length) === href) {
$(this).closest('li').addClass('active');
}
});
$(".sub_navmenu ul li").click(function(){
$(this).find('a').toggleClass('active');
});
}
.navigation {
list-style-type: none;
}
.sub_navmenu > ul {
list-style-type: none;
}
.active {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul id="navmenu" class="navigation">
<li >
Home
</li>
<li class="sub_navmenu">
About me
<ul>
<li>
Item 1
</li>
<li>
Item 1
</li>
<li>
Item 1
</li>
</ul>
</li>
<ul>
Is this is what are you expecting to do?

Find #ID, AddClass by URL in Navigation Jquery

I am making a website. I want to go from link to next page with ID. Like the following
Page Name: index.html
Rings
Page Name: collection.html
<ul class="nav navbar-nav" id="nav">
<li id="rings" class="active">Rings</li>
<li id="earrings">Earrings</li>
<li id="neckwears">Neckwear</li>
<li id="purses">Purses</li>
<li id="mini">Set an mini set</li>
</ul>
I try to take code and implement in this but not get any success.
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$(function(){
var current = location.pathname;
var url = window.location.hash;
$('#nav li').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
});
});
});
</script>
I wan to put active class automatically in #nav list via using URL # value.
You can just use the pathname as a selector, like this: $('#nav li#'+current)
There is no reason to loop through all of them.
$(document).ready(function() {
$(function() {
var current = "rings"; //location.pathname
$('#nav li#' + current).addClass("active");
});
});
.active a {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav navbar-nav" id="nav">
<li id="rings" class="">Rings</li>
<li id="earrings">Earrings</li>
<li id="neckwears">Neckwear</li>
<li id="purses">Purses</li>
<li id="mini">Set an mini set</li>
</ul>
You were just comparing to the wrong variable. Just change your code to the below
$(document).ready(function () {
$(function(){
var current = location.pathname;
var url = window.location.hash;
$('#nav li').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if("#" + $this.attr('id') == url){
$this.addClass('active');
}
});
});
});

Using of Local storage with the help of JS or jQuery

Here is my
$(".myLinks > li > a").click(function(){
$("a.activeLink").removeClass("activeLink");
$(this).addClass("activeLink");
});
.activeLink{color:red!important}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="myLinks">
<li id="nav1">Link 1</li>
<li id="nav2">Link 2</li>
<li id="nav3">Link 3</li>
<li id="nav4">Link 4</li>
<li id="nav5">Link 5</li>
</ul>
I want to store last visited/ clicked link into the local storage. And when do I refresh the browser, the visited link will be shown as red colored. What will be the code for this?
Output after storing it in local storage and browser refreshed
Here is a quick and sample snippet to work with:
// Let's process when `DOM is ready`
$(document).ready(function() {
// try-get the active item from `local storage`
var activeLinkParentId = window.localStorage.getItem("activeLinkParentId");
if (activeLinkParentId) {
$("#" + activeLinkParentId + "> a").addClass("activeLink");
}
// Add click handler to the `anchor` tags
$(".myLinks > li > a").click(function() {
$("a.activeLink").removeClass("activeLink");
window.localStorage.setItem("activeLinkParentId", $(this).parent().attr("id"));
$(this).addClass("activeLink");
});
});
.activeLink {
color: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="myLinks">
<li id="nav1">
Link 1
</li>
<li id="nav2">
Link 2
</li>
<li id="nav3">
Link 3
</li>
<li id="nav4">
Link 4
</li>
<li id="nav5">
Link 5
</li>
</ul>
you can use following function to get or set local storage values
function setStorageItem(key, value)
{
localStorage.setItem(key, value);
}
function getStorageItem(key)
{
return localStorage.getItem(key);
}
and you can use it like following
$(".myLinks > li > a").click(function(){
$("a.activeLink").removeClass("activeLink");
$(this).addClass("activeLink");
setStorageItem("yourwebsitename_lastvisitedlink",$(this).attr("href"));
setStorageItem("yourwebsitename_lastvisitedlinkID",$(this).parent("li").attr("id"));
});
check this link for more information
This will store a "last" key in local storage with the ID of the parent li for the clicked link. When they click on a link, it will overwrite whatever is in the key currently, meaning it will always reflect the last link the user clicked.
$(function() {
var id = localStorage.getItem('last');
$('#' + id).addClass('activeLink');
});
$(".myLinks > li > a").click(function(){
/* start local storage stuff */
var id = $(this).parent().attr('id');
localStorage.setItem('last', id);
/* end local storage stuff */
$("a.activeLink").removeClass("activeLink");
$(this).addClass("activeLink");
});

Trying to add active class to menu item

I've spent 2 hours trying to create an active menu with no success, so I figured I would ask for help. I have an html menu, some js & css...
$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/") + 1);
$("#index li a").each(function() {
if ($(this).attr("href") == pgurl || $(this).attr("href") == '')
$(this).addClass("active");
})
});
.active { font-weight:bold;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='index'>
<div class='container'>
<div class='top'>
<h1><a href='/' title='The Maths Project'>The Maths Project</a></h1>
</div>
<ul class='section active_section' id='section_2'>
<li><span id='section_title_2' class='section_title'><a href='#' id='section_link_2'>Against the odds.</a></span>
<ul>
<li id='exhibit_106' class='exhibit_title'> → Introduction
</li>
<li id='exhibit_83' class='exhibit_title'><a href='../against-the-odds/deriving-functions'> → Deriving functions</a>
</li>
<li id='exhibit_83' class='exhibit_title'><a href='../against-the-odds/exploiting-odds'> → Exploiting odds</a>
</li>
</ul>
</li>
</ul>
<ul class='section' id='section_3'>
<li><span id='section_title_3' class='section_title'><a href='http://themathsproject.co.uk' id='section_link_3'>Remembering everything.</a></span>
<ul>
<li id='exhibit_104' class='exhibit_title'><a href='../against-the-odds/black-swans'>black swans</a>
</li>
<li id='exhibit_72' class='exhibit_title'><a href='../against-the-odds/in-here-it-is-yesterday'>in here it is yesterday </a>
</li>
</ul>
</li>
</ul>
</div>
</div>
When the user is on a specific page, the "a" link which they have clicked should become bold. However, for whatever reason it's not working.
I would greatly appreciate any help,
Regards,
Jack
I am not clear with your question but do you want set active class to menu, so you try the below code
$('#navlist a').click(function(e) {
e.preventDefault(); //prevent the link from being followed
$('#navlist a').removeClass('selected');
$(this).addClass('selected');
});
.nav {
color: green;
}
.selected {
color: red;
}
.san ul li{
float:left;
margin-right: 25px;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<div class="san">
<ul id="navlist">
<li><a class="nav" href="">Home</a></li>
<li><a class="nav" href="">About Us</a></li>
<li><a class="nav" href="">Services</a></li>
<li><a class="nav" href="">Contact</a></li>
</ul>
</div>
This line gets the page name:
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/") + 1);
you need to apply the same logic to each of your links to see if they match:
$("#index li a").each(function() {
var aurl = $(this).attr("href").substr($(this).attr("href")
.lastIndexOf("/")+1);
if (aurl == pgurl || aurl == '')
$(this).addClass("active");
})
Snippet below (tweaked to match as location.href won't match)
$(function() {
//var pgurl = window.location.href.substr(window.location.href
// .lastIndexOf("/") + 1);
var locationhref = "mysite.com/against-the-odds/introduction"
var pgurl = locationhref.substr(locationhref.lastIndexOf("/")+1);
$("#index li a").each(function() {
var aurl = $(this).attr("href").substr($(this).attr("href")
.lastIndexOf("/")+1);
//console.log(aurl)
if (aurl == pgurl || aurl == '')
$(this).addClass("active");
})
});
.active { font-weight:bold;color:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='index'>
<div class='container'>
<div class='top'>
<h1><a href='/' title='The Maths Project'>The Maths Project</a></h1>
</div>
<ul class='section active_section' id='section_2'>
<li><span id='section_title_2' class='section_title'><a href='#' id='section_link_2'>Against the odds.</a></span>
<ul>
<li id='exhibit_106' class='exhibit_title'> → Introduction
</li>
<li id='exhibit_83' class='exhibit_title'><a href='../against-the-odds/deriving-functions'> → Deriving functions</a>
</li>
<li id='exhibit_83' class='exhibit_title'><a href='../against-the-odds/exploiting-odds'> → Exploiting odds</a>
</li>
</ul>
</li>
</ul>
<ul class='section' id='section_3'>
<li><span id='section_title_3' class='section_title'><a href='http://themathsproject.co.uk' id='section_link_3'>Remembering everything.</a></span>
<ul>
<li id='exhibit_104' class='exhibit_title'><a href='../against-the-odds/black-swans'>black swans</a>
</li>
<li id='exhibit_72' class='exhibit_title'><a href='../against-the-odds/in-here-it-is-yesterday'>in here it is yesterday </a>
</li>
</ul>
</li>
</ul>
</div>
</div>
Try following and check if it works.
$(function() {
var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$("#index li a").each(function() {
var href = "";
if($(this).attr("href") != '')
href = $(this).attr("href").substr(($(this).attr("href").lastIndexOf("/")+1);
if (href == pgurl || href == '')
$(this).addClass("active");
})
});
Just traverse the whole links and when any link will clicked then change the font-weight:normal to all links and then apply the font-weight:bold to currently clicked link.
$().ready(function () {
$("ul>li").click(function () {
$("ul>li").css("font-weight", "normal");
$(this).css("font-weight", "bold");
});
});

How to hide parent <li> if all the children are hidden in jquery

I am new in Jquery
My Webpage structure is like this
<div id="MenuSection">
<ul>
<li>Master // Main Menu
<ul>
<li>Master1</li>
<li>Master2</li>
<li>Master3</li>
</ul>
</li>
<li>Transaction // Main Menu
<ul>
<li>Transaction1</li>
<li>Transaction2</li>
<li>Transaction3</li>
</ul>
</li>
<li>Report // Main Menu
<ul>
<li>Report1</li>
<li>Report2</li>
<li>Report3</li>
</ul>
</li>
</ul>
</div>
I want that when all the children of any Parent(main menu) are hidden, Parent should also be hidden. Let's say if Report1, Report2, Report3 are hidden then Parent that is "Report" should also be hidden.
How can I achieve this through Jquery ?
One way is to iterate over each main menu li to see if its children are all :visible:
$("#MenuSection>ul>li").each(function() {
if ($(this).find(">ul>li:visible").length == 0) {
$(this).hide();
}
});
there are other ways to do this, such as using .filter or .map, but this should get you what you need.
Given the nested ul's the above uses > to ensure only the directly ul>li children are processed. If you have multiple levels, you might need to change accordingly, eg for the first: #MenuSection li would apply to all lis and the second .find(">ul>li:visible") only looks at direct li children.
$("#MenuSection>ul>li").each(function() {
if ($(this).find("li:visible").length == 0) {
$(this).hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="MenuSection">
<ul>
<li>Master
<ul>
<li>Master1</li>
<li>Master2</li>
<li>Master3</li>
</ul>
</li>
<li>Transaction
<ul>
<li>Transaction1</li>
<li>Transaction2</li>
<li>Transaction3</li>
</ul>
</li>
<li>Report
<ul>
<li style='display:none'>Report1</li>
<li style='display:none'>Report2</li>
<li style='display:none'>Report3</li>
</ul>
</li>
</ul>
</div>
JavaScript does it fairly easy. You would need expand on this to execute this check every on the relevant list every time you hide or show a list item.
function isHidden(array) {
for(var i = 0; i < array.length - 1; i++) {
if(array[i+1].style.display != "none") {
return false;
};
};
return true;
};
var children = document.getElementById("report").getElementsByTagName("LI");
if (isHidden(children)) {
document.getElementById("report").style.display = "none";
};
You can use the the .is(':visible')
See the code:
(function($) {
$(document).ready(function() {
var $mainLinks = $('#MenuSection > ul > li');
$.each($mainLinks, function() {
if (!$(this).find('li').is(':visible')) {
$(this).hide();
}
});
});
})(jQuery);
#MenuSection > ul > li:last-child li {
display: none;
}
#MenuSection > ul > li:first-child li:first-child {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="MenuSection">
<ul>
<li>Master // Main Menu
<ul>
<li>Master1</li>
<li>Master2</li>
<li>Master3</li>
</ul>
</li>
<li>Transaction // Main Menu
<ul>
<li>Transaction1</li>
<li>Transaction2</li>
<li>Transaction3</li>
</ul>
</li>
<li>Report // Main Menu
<ul>
<li>Report1</li>
<li>Report2</li>
<li>Report3</li>
</ul>
</li>
</ul>
</div>

Categories

Resources