Reputation: 43
this is in reference to this other thread as well: jQuery - If URL matches href then move LI to top of UL?
Jquery code:
//set var to current url
var url = window.location.toString();
//if url matches li's anchor then bring it to the top of the list
$('.nav li a').each(function(){
var myHref= $(this).attr('href');
if( url == myHref) {
$(this).closest("li").prependTo(".nav");
}
});
The HTML is just from a Wordpress Navigation so something like:
<navrole="navigation">
<ul>
<li>
<a href="">
The navigation points to categories, and the url matches the href's fine and the code works. But, I cannot figure out how to get the code to also fire when I am in a child page of a category, for example when the url is:
domain.com/category-name/child-page
If I can get the Jquery to only detect the first pathname past the domain, then I will be golden. Anything past the first pathname could be omitted or setup as a wild card or something.
Any ideas?
Upvotes: 4
Views: 2121
Reputation: 144689
You can try using attribute contains selector
:
var dom = document.domain;
var f = location.pathname.split('/')[1];
var url = dom + "/" + f;
$('.nav li a[href*="'+url+'"]').closest("li").prependTo(".nav");
Upvotes: 2
Reputation: 4264
I had implemented such a technique for my website. Here's how I did it:
var Tabs = ["Tab1", "Tab2", "Tab3", "Tab4", "Tab5"];
var pathname = document.location.pathname;
for (var i = 0; i < Tabs.length; i++) {
//RegExp to check the name after first '/'
var TabRE = new RegExp("^\/(" + Tabs[i] + ")");
if (TabRE.test(pathname)) {
//Tab identified!!!
}
Or if you simply want to get the "first pathname past the domain", you can simply do
var path = (document.location.pathname).substring(1);
var name;
if (path.indexOf('/') >= 0)
name = path.substring(0, path.indexOf('/'));
else name = path;
Upvotes: 0
Reputation: 5674
You're going to want to use the pathname to access everything after your domain name. Then split the string on slashes.
var pathname = window.location.pathname; //"category-name/child-page"
var path_components_arr = pathname.split("/"); //array containing components from above, in order.
Then path_components gives you an array, each element being a part of the path between the slashes. Sounds like you would only need the first element of that array... I'm sure you can take it from there!
Hope that helps!
Upvotes: 0