How to add selected states to your navigation using jQuery.

Here’s a simple jQuery solution for adding selected states to your navigation.

The sample HTML looks like this:

And the sample CSS:

		li {
			background-color: white;
			color: black;
			padding: 5px 10px;
		li.selected {
			background-color: black;
			color: white;

And the corresponding jQuery:

		$(document).ready(function() {

			// store url for current page as global variable
			current_page = document.location.href

			// apply selected states depending on current page
			if (current_page.match(/home/)) {
				$("ul#navigation li:eq(0)").addClass('selected');
			} else if (current_page.match(/services/)) {
				$("ul#navigation li:eq(1)").addClass('selected');
			} else if (current_page.match(/about/)) {
				$("ul#navigation li:eq(2)").addClass('selected');
			} else if (current_page.match(/information/)) {
				$("ul#navigation li:eq(3)").addClass('selected');
			} else if (current_page.match(/contact/)) {
				$("ul#navigation li:eq(4)").addClass('selected');
			} else { // don't mark any nav links as selected
				$("ul#navigation li").removeClass('selected');


How does it work?

First we capture the url of the current page in a variable. Then we use that variable to write conditions based on a regular expression (e.g. if the current url contains the word ‘about’). Finally, we use the :eq(index) selector to target the corresponding <li> and add a class of selected.

The only thing that’s remotely tricky here is the :eq(index) selector. This allows you to use an index to target a specific element within a larger array of matched elements.

So in our example, ul#navigation li would return an array of all five <li> elements whereas ul#navigation li:eq(4) would return only the fifth <li>. This saves us the trouble of having to apply a unique id to each list item.

A few gotchas.

  • Make sure your regular expression matchers are not too general or you might end up adding selected states to the wrong pages. For example, this might not be a good solution for a blog where the slugs correspond to post tiles.
  • Make sure to include the most recent version of jQuery in your head element.
  • Make sure jQuery is loaded before the script for your selected navigation.
  • Don’t forget to place your script inside the document ready function. Otherwise your script will run before the DOM is fully loaded – and do nothing.



Your thoughts?