Change <li> class of the current link - javascript

I have following code to change the class of li if the browser url is the same string as the a href tag within that li.
The problem with my code is that it changes the class for all li elements, not just the ones containing the specific url.
Javascript :
$(document).ready(function() {
$("#subnav a").each(function() {
if ($(this).attr('href') == document.URL) {
$('li').addClass("selected");
}
});
});
html:
<div id="subnav">
<ul class="tabrow">
<li> Players
</li>
<li> Guilds
</li>
<li>Master Level
</li>
<li>Voters
</li>
<li>Online
</li>
</ul>
</div>
solution if anyone needed. Thanks to nem035
$(document).ready(function() {
$("#subnav a").each(function() {
if ($(this).attr('href') == document.URL) {
$(this).parent().addClass("selected");
}
});
});

Your issue is that you are using the selector $('li'), which selects all <li> elements, not just the parent of the current <a> whose url you are comparing.
This is probably what you should do:
if($(this).attr('href') == document.URL){
$(this).parent().addClass("selected");
}

Insert u php:
<?php
$url = $this->config->base_url.'rankings/all';
if($_SERVER['REQUEST_URI'] !== $url) echo(' class="selected" ');
?>

Related

how to add class to list item

jQuery(function($) {
var path = window.location.href;
$('ul li').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
<ul id="nav" class="nav navbar-nav">
<li class="active">A</li>
<li>Bs</li>
<li>C </li>
</ul>
I want to change the class="active" in list items on click.
<li id="a" >A</li>
UsingĀ $('#a').attr('class', 'active')
Output:
<li id="a" class='active' >A</li>
The problem is you're checking the li element for its href property, which doesn't exist. You need to check the a tag inside of the li element for the href property like this:
if ($(this).find('a').attr('href') === path) {
$(this).addClass('active');
}
You could use:
$(this).toggleClass('class1 class2')
If you are looking to change an active class and html pages this would be an effective way to do this.If you just want to change the active class use only the first 4 lines of code.
$( document ).ready(function() {
$(".nav li").click(function() {
$(".nav li.active").removeClass("active");
$(this).addClass("active");
if($(this).attr('id')=="yourfirstlinkid"){
document.getElementById("content").innerHTML='<object type="text/html" data="yoursite" height="90% width="90%" ></object>';
}else if($(this).attr('id')=="otherid"){
document.getElementById("content").innerHTML='<object type="text/html" data="othersite"></object>';
}else{
document.getElementById("content").innerHTML='<div/>';
}
});
});
And then all you need to do to your html is
<ul class="nav">
<li class="active" id="whateveryouwant">A</li>
<li id="whateveryouwant" >Bs</li>
<li id="whateveryouwant">C</li>
</ul>
<div align= "center" id="content"></div>
Another thing I want to add is never use herf for a nav bar because the navbar js code will change never allowing it to change it's current active class.

Add active class to nav li depending on url?

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.

Prevent default only on some levels

I am making a menu that has submenu. When I click on a menu item I am using prevent default because it is a tags, but on the submenu level I don't want to prevent default. I haven't been able to figure out how to make it work so it doesn't affect the top level.
<div id="block-menu-block-2">
<ul class="menu">
<li>
1
</li>
<li>
2
<ul class="menu">
<li>2.1</li>
<li>2.2</li>
<li>2.3</li>
<li>2.4</li>
</ul>
</li>
<li>
3
<ul class="menu">
<li>3.1</li>
<li>3.2</li>
<li>3.3</li>
<li>3.4</li>
</ul>
</li>
<li>
4
</li>
<li>
5
</li>
<li>
6
<ul class="menu">
<li>6.1</li>
</ul>
</li>
</ul>
</div>
Here is the jQuery
$('#block-menu-block-2 ul li').on("click", function() {
if ($(this).children().is('ul')) {
if ($(this).find('ul').is(':visible')) {
$(this).find('ul').hide("blind");
$(this).removeClass('menuItemSelected');
$(this).find('ul').removeClass('menuItemSelected');
} else {
$(this).parent().find('li ul').hide("blind");
$(this).parent().find('.menuItemSelected').removeClass('menuItemSelected');
$(this).find('ul').show("blind");
$(this).addClass('menuItemSelected');
$(this).find('ul').addClass('menuItemSelected');
};
event.preventDefault()
}
});
Here is a codepen for reference: http://codepen.io/mathiasha/pen/bVpMyo
Added some stuff. Changed some stuff. Couldn't paste into codepen from my phone so this might not work. Code first, then word wall.
$('#block-menu-block-2 ul li').each (function () {
var $this = $(this);
if ($this.find ('ul:first').length > 0) {
$this.click (function () {
if ($this.find ('ul:visible').length > 0) {
$this.removeClass ('menuItemSelected').find ('ul').removeClass('menuItemSelected').hide ('blind');
} else {
$this.parent ().find ('ul li').hide ('blind');
$this.parent ().find('.menuItemSelected').removeClass ('menuItemSelected');
$this.addClass ('menuItemSelected').find ('ul').show ('blind').addClass ('menuItemSelected');
}
});
}
});
$('#block-menu-block-2 > ul > li > a').click (function (e) {
if ($(this).find ('ul:first').length > 0)
e.preventDefault ();
});
The real answer lies in only putting the preventDefault only on the a tag and only when it is the immediate child of a li tag tjat is the immediate child of a ul tag that is the immediate child of the block-menu. See the last 3 lines.
The rest of the code below should only add the click listener to li tags with ul tags inside. Tried to use chaining to limit the number of jQuery objects created. Might have messed up what it was doing. You only really need to remove preventDefault from where it is and than use the last 3 lines.
Can you not add a class to your submenu triggers, e.g. .submenu-trigger, and then use the following jQuery:
$(document).on('click', function(e) {
if ($(e.target).hasClass('submenu-trigger')) e.preventDefault();
});
Ignoring all the other menu manipulation and putting the event on <a> tags you can simply check if the <a> has a sibling <ul> and if it does prevent default
$('#block-menu-block-2 a').click(function(e){
if( $(this).siblings('ul').length ){
e.preventDefault();
}
// menu manipulation code
});

For each li in list that contains span with text, remove another span from within that li

I have a list of items.
In each list item, I have spans.
I want to check if one span contains a string (in this case is : "Account"), to remove another span from that List item only. I am selecting the items by Class, not by Id.
I tried this code:
$("ul").find('li .productRelatedToAdditional:contains("Account")').each(function(){
if ($(".productRelatedToAdditional:contains('Account')").length > 0) {
$(".productRelatedToAdditional").remove();
$(".productRelatedTo").remove();
}
});
but it is not working. It is removing the elements from all List items.
So I want to remove the span with the Class "productRelatedTo" and the element "productRelatedToAdditional" only from the list items where the span with the class "productRelatedToAdditional" contains the word "Account"
Thank you very much
Try this : find parent li of productRelatedToAdditional matched, then find productRelatedTo and remove it.
$("ul").find('li .productRelatedToAdditional:contains("Account")').each(function(){
var $parentLi = $(this).closest('li');
$(this).remove();
$parentLi.find(".productRelatedTo").remove();
});
see also working code snippet
(function($) {
$('li').each(function() {
var string = $(this).find('.productRelatedToAdditional').html();
console.log(string);
if (string.toLowerCase().indexOf("active") >= 0) {
$(this).find('.productRelatedTo').remove();
$(this).find('.productRelatedToAdditional').remove();
}
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<ul>
<li>
<span class="productRelatedTo">hello1</span>
<span class="productRelatedToAdditional">active</span>
</li>
<li>
<span class="productRelatedTo">hello2</span>
<span class="productRelatedToAdditional"></span>
</li>
<li>
<span class="productRelatedTo">hello3</span>
<span class="productRelatedToAdditional">aCtiVe</span>
</li>
<li>
<span class="productRelatedTo">hello4</span>
<span class="productRelatedToAdditional"></span>
</li>
</ul>
</body>
</html>
this should do the job:
$('li').each(function(){
var string = $(this).children('.productRelatedToAdditional').html();
if (string.toLowerCase().indexOf("active") >= 0){
$(this).children('.productRelatedTo').remove();
$(this).children('.productRelatedToAdditional').remove();
}
});
greetings timotheus
$(document).ready(function(){
$("li .productRelatedToAdditional:contains('Account')").each(function(){
$(this).siblings(".productRelatedToAdditional, .productRelatedTo").remove();
});
});
http://jsfiddle.net/h9wj6bx7/2/

Comparing URL to links

I have the following HTML:
<ul class="vertical_menu no_select">
<li class="edge_top"> </li>
<!-- Menu Items Here -->
<li class="not_selected"><a class="selection_link" href="index.htm">Home</a></li>
<li class="not_selected"><a class="selection_link" href="index.htm">Subitem 1</a></li>
<li class="not_selected"><a class="selection_link" href="index.htm">Subitem 2</a></li>
<!-- Menu Items End Here -->
<li class="edge_bottom"> </li>
</ul>
Now, the links with the class "selection_link" need to have the li element (their parent) to have a new class "selected" if the current url matches the href value inside of the anchor tag. I can get the full URL but I don't know how to use that to help seeing as there could be more than one page with the same name at different directory levels.
Thanks if you can help! I'm using jQuery with all of this so feel free to provide me with jQuery examples!
Check out the jsFiddle. This should do the trick:
$("ul.vertical_menu li a").each(function() {
if (this.href == window.location.href) {
$(this).parent().toggleClass("not_selected selected");
}
});
$('.selection_link').each(function() {
if($(this).attr('href') === window.location.pathName.substring(1)) {
$(this).parent().attr("class", "selected");
}
});
not tested, but it'll it should start you off. substring is because pathname starts with '/' you could just put that in your href's too
or this...
$('.vertical_menu a').each(function() {
if (location.href.search(this.attr('href')) != -1) {
$(this).parent().addClass('selected');
}
});

Categories

Resources