Add class to another page attribute using URL id - Jquery - javascript

I have attached id with URL. Ex: When I click Link 1, it has #tab-2 id and it takes me to landing page. In landing page I have find which element has #tab-2 id then i have to add class .active.
I tried but no luck. Please any one correct my code. Thanks
JS Fiddle link
HTML
<div class="menu">
<ul>
<li>LINK 1</li>
<li>LINK 2</li>
<li>LINK 3</li>
</ul>
</div>
Landing Page
<div class="tab">
<ul>
<li><a id="tab-2" class="active" >LINK 1 Content</a></li>
<li><a id="tab-44" >LINK 2 Content</a></li>
<li><a id="tab-74" >LINK 3 Content</a></li>
</ul>
</div>
Jquery
$(document).ready(function(){
$(".menu ul li a").each(function(){
var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);
var land = $('.tab').find("id");
if( land == id ) {
$('this').addClass('active');
}
})
});

Assuming I've understood your requirement, you can retrieve the hash value from the URL of the page using window.location.hash. You can then use that to directly select the required element and add a class to it on load of the new page:
$(function() {
var id = window.location.hash; // = '#tab-2', in your first link.
$(id).addClass('active');
});

Try this:
http://www.w3schools.com/jsref/prop_loc_hash.asp
$(document).ready(function(){
var hash = window.location.hash;
$(hash).addClass('active');
});
I hope it helps.

Replace $('this').addClass('active'); by $(this).addClass('active');
if( land == id ) {
$(this).addClass('active');
}

Use event.preventDefault it prevents the default action and Use window.location.hash to getting the hash element in the url
$(".menu ul li a").click(function(event){
event.preventDefault();
var url = window.location.hash;
$(".tab ul li a").removeClass('active');
$(url).addClass('active');
})

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.

jQuery script wont add active class

I got this jQuery script that's supposed to add the class "active" to my li's, but it doesn't. The script is as follows:
jQuery(function() {
var pgurl = jQuery(location).attr('href');
console.log(pgurl);
jQuery("ul.pagesubmenu-ul li a").each(function(){
if(jQuery(this).attr("href") == pgurl)
jQuery(this).parent().addClass("active");
})
});
I really don't know why it isn't working. I'm trying to use it on this page (In the subnav below the main navigation).
Thanks in advance!
instead of looping all your links, you can directly select it with jquery by its href attribute:
$(function() {
$("a[href='" + location.href + "']").parent().addClass('active');
});
Note that location.href will return the full url, with host and scheme, if you are using relative urls in your site:
$(function() {
$("a[href='" + location.pathname + "']").parent().addClass('active');
});
Also, you can use some characters as wildcards:
= is exactly equal
!= not equal
^= starts with
$= ends with
*= contains
~= contains word
|= starts with prefix
It's not getting an exact match on any of those links. pgurl is showing http://xn--fnpark-pua9l.dk/konference-ny/, however the <a> tags don't have the trailing slash (http://xn--fnpark-pua9l.dk/konference-ny). Try cleaning up the url before comparing the strings. Here is a thread that will allow you to do that: https://stackoverflow.com/a/2541083/5169684
Why not working? Can you do a jsfiddle with your navigation structure...
HTML
<ul class="page">
<li>Link
<ul class="subpage">
<li>Sub Link</li>
<li>Sub Link</li>
<li>Sub Link</li>
</ul>
</li>
<li>Link</li>
<li>Link</li>
<li>Link</li>
<li>Link</li>
</ul>
JQUERY
jQuery(function() {
$("ul.page li ul.subpage li a").each(function(){
$(this).addClass('active');
});
});
https://jsfiddle.net/xp315ydq/

Variable not being set correctly; how to fix?

I want my JQuery to select one of the navigation links—based on the page that I'm on—and then I want it to move it to the top of the list.
This is the HTML of my navigation bar:
<nav>
<ul id=nav>
<li>Home</li>
<li>Skillsets</li>
<li><icon>Gallery</li>
<li>About</li>
<li>Contact</li>
</ul>
</nav>
This is the JQuery I'm using to try and reorder the list:
var page = document.location.pathname.match(/[^\/]+$/)[0];
$(document).ready(function(){
var ul = $('nav').children('ul'),
li = ul.children('li'),
href = $('a[href*='+page+']');
//move element to top
ul.prepend(href.parent());
});
It isn't working and I would assume that it's because the href variable isn't being set correctly. alert(href); and alert(href.parent()); output nothing.
Any ideas? Thanks!
As #user3064914 said, you missed '#', but you missed quotes either:
<ul id = "nav">
var href = $('a[href*="'+page+'"]');
EDIT
Also, you can write a bit shorter with child selectors:
var ul = $('nav > ul'),
href = ul.find('> li a[href*="' + page + '"]');
ul.prepend(href.parent());
Try this, it will work.
<script>
var page = document.location.pathname.match(/[^\/]+$/)[0];
$(document).ready(function()
{
var href = $('a[href='+'"'+page+'"'+']').parent();
var parent = $("#nav");
var childToMoveLast = href.remove();
parent.prepend(childToMoveLast);
});
</script>
Here is the HTML
<nav>
<ul id='nav'>
<li>Home</li>
<li>Skillsets</li>
<li><icon>Gallery</li>
<li>About</li>
<li>Contact</li>
</ul>
</nav>

How to add a class to an element using jQuery and javascript?

I have the HTML code as given below to add the navigation to my site. (Note that the list is nested)
<div id="navigation">
<ul>
<li>Home</li>
<li>About us</li>
<li>Help</li>
<li>DropDown
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
</ul>
</li>
<li class="last">A Last Link Text</li>
</ul>
</div>
I want to show the currently active page link in new color. So the corresponding list item should have the class active and I use the CSS to change the color. For example, if the default.html is the currently opened page, the code should be <li class=“active”>Home</li>.
How to do that in jQuery and JavaScript (I need both for two different websites).
Can anyone help me?
Thanks for your help.
Get your URL / Parse it:
var pathname = window.location.pathname;
Then add the class:
Jquery:
$(element).addClass('classname');
JS: How do I add a class to a given element?
Try this
$(document).ready(function () {
var url = location.href;
$('#navigation li a').each(function () {
var thisHref = this.getAttribute('href');
if (thisHref !== '#' && url.indexOf(thisHref) !== -1) {
$(this.parentNode).addClass('active');
return;
}
});
});

Categories

Resources