Reputation: 79
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!
Upvotes: 2
Views: 71
Reputation: 21759
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
Upvotes: 4
Reputation: 536
Why not working? Can you do a jsfiddle with your navigation structure...
HTML
<ul class="page">
<li><a href="1">Link</a>
<ul class="subpage">
<li><a href="#">Sub Link</a></li>
<li><a href="#">Sub Link</a></li>
<li><a href="#">Sub Link</a></li>
</ul>
</li>
<li><a href="2">Link</a></li>
<li><a href="3">Link</a></li>
<li><a href="4">Link</a></li>
<li><a href="5">Link</a></li>
</ul>
JQUERY
jQuery(function() {
$("ul.page li ul.subpage li a").each(function(){
$(this).addClass('active');
});
});
https://jsfiddle.net/xp315ydq/
Upvotes: 0
Reputation: 763
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
Upvotes: 1