Skip to content

Instantly share code, notes, and snippets.

@cobbman
Last active December 14, 2015 07:59
Show Gist options
  • Save cobbman/5054171 to your computer and use it in GitHub Desktop.
Save cobbman/5054171 to your computer and use it in GitHub Desktop.
jQuery: Highlight current navigation element. Useful for highlighting nav elements when you are on the "current" page of a dynamic site, where the same header file is loaded for every page.
// get the page url of current page
var currentPage = location.href;
//alert("current page is " + currentPage);
// compare page url with nav links. Add css class 'current' to current page and remove from others
$("ul#topnav li a").each(function() {
//console.log(this.href);
if ( currentPage.indexOf( this.href ) > -1 ) { // if this link url is found in the page url then...
$('li.current').removeClass('current'); // find the list item with class of 'current' and remove the class
$(this).parent().addClass('current'); // add 'current' to parent of THIS element
}
});
@cobbman
Copy link
Author

cobbman commented Mar 18, 2013

Remember to add some unique styling in your CSS for your 'current' class. Maybe make the text BOLD or set a different background color for the tab. The possibilites are endless.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment