Skip to content

Instantly share code, notes, and snippets.

@jalexanderfox
Last active December 16, 2015 21:59
Show Gist options
  • Save jalexanderfox/5503819 to your computer and use it in GitHub Desktop.
Save jalexanderfox/5503819 to your computer and use it in GitHub Desktop.
Automatically indicate (highlight or style) the current navigation items for current the url (jQuery help). window.location.pathname compared to anchor hrefs of each navigation item.
//NOTE: you should put this in a function (closure)
//characters not allowed in pagename
var x_chars = ['?', '&', '#'];
/*
extract_pagename helps insure that when names are used for comparison,
the names will be clean and clear of any unwanted query strings, hashes or other special characters
though this method is not necessary for
window.location.pathname, it might be necessary for
anchor href values that could contain these special characters.
*/
function extract_pagename(name) {
if (name !== "") {
var special_chars = new RegExp('[' + x_chars.join('') + ']');
if(name.match(special_chars)){
for(var i = 0; i < x_chars.length; i++) {
name = name.split(x_chars[i])[0]; //return left side of characters not welcome as page names
}
}
}
return name;
}
function get_page_name_from_url(url) {
var arr_url = url.split('/');
var pagename = extract_pagename(arr_url[arr_url.length - 1]) || arr_url[arr_url.length - 2]; //get the last part (if last part is falsy, return second to last part, this happens if the url has a trailing "/")
return pagename;
}
var current_page_name = get_page_name_from_url(window.location.pathname);
/*
jQuery specific methods, everything above this point is native js and does not require a library
We get all navigation item links ('.navigation ul a') and filter to see if
the url is equal to the current url, if so we set ALL of the parent 'li' elements with the class 'active'
*/
jQuery('.navigation ul a').filter(function() {
return get_page_name_from_url(this.href) === current_page_name;
}).parents('li').addClass('active');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment