February 14

Dynamic Current Page Class, a jQuery solution

Not so long ago, I ran into a very common current-page link problem. All I needed was an extra class added to an li element in order to clearly represent the current page in the navigation. I looked for a solution and came across this one in A List Apart. The solution, though clean and clever, would not work for me as I was unable to add a snippet of PHP to all the necessary pages. So, I turned to a web designer’s next best friend (CSS being the best).

Assumptions

I am going to assume that you are using a CMS, which has some sort of head item (header.php) applied across a certain theme. Next, I am also going to assume that you know and have a copy of jQuery ready to be used. jQuery is not absolutely necessary but it definitely reduces a few lines of code and is easy to read.

Now, for the How-to

Let’s begin by gathering all the URLs which constitute our navigation and create some JavaScript variables in order to store them. Let’s also create a variable that gathers the current URL. So far, you should have something like this:

$(document).ready(function() { var link_1 = "http://thiismyfirsturl.com"; var link_2 = "http://thiismysecondurl.com"; var current_url = location.href; });

We are almost done, this is a very simple script after all. Now, all we have left to do is add a few simple if statements and a create a name for the class we will be adding (I used current, seemed appropriate to me). Here is what the final product looks like:

$(document).ready(function() { var link_1 = "http://thiismyfirsturl.com"; var link_2 = "http://thiismysecondurl.com"; var current_url = location.href; if (current_url == link_1) { $("#yourTargetID").addClass("current"); } else if (current_url == link_2) { $("#yourTargetID").addClass("current"); } });

As you can see, it is a very simple procedure. Remember that if you are using jQuery in combination with other JavaScript libraries, you must replace the “$” symbol for “jQuery.” Also remember to change the “#yourTargetID” for your actual target’s ID or class.

Final Remarks

I hope this is of some help to some one. If you have any problems getting the script to work please don’t hesitate on leaving a comment or contacting me. Also, remember that you will need to add CSS rules for the new “current” class.

stumble upon icon

Leave Your Thoughts