jQuery – Add a class name to navigation menu, depending on the active page

Problem: When you navigate to a page on your website, you’d like for the appropriate main navigation menu item to show as active.

HTML: The HTML you’ll want to use can be a simple unordered list, with UL LI A elements.

CSS: If you’re going for a horizontal navigation menu, you’ll need to float or display: inline the LI elements. You’ll want to style the active/selected state, as well as the hover state, at the very least. Consider styling the font, colors, etc. to your liking.

jQuery: The code will cycle through each link in your menu, and then compare the href attribute to the location/path of the page you’re on. If the href and the path of the page are matched, then the code will add a class name to the element.

Demo: This demo will not show the ‘is-selected’ class on any of the nav links. This is because we cannot navigate to any of the linked pages in the nav since this is just a demo via CodePen.io

See the Pen Nav menu – active class name by Cindy Lee (@cindylee) on CodePen.0