jQuery - Marking Current Link Active

Hold on Cowboy

This blog post is pretty old. Be careful with the information you find in here. It's likely dead, dying, or wildly inaccurate.

Have you ever wanted to have a link show as “Active” when a users is on that link? If you have a navigation at the top of your site and you want to visually indicate that the visitor is on that link, then you would usually add and “active” class to that link and style it appropriately.

This little snippet of code will do that.

<code> $(document).ready(function(){ var path = location.pathname.substring(1); if ( path ) { $(‘.header a[href$=“’ + path + ‘”]’).addClass(‘active’); } });

</code>

location.pathname.substring(1); will return the url that you are on, subtract the hostname name. a[href$="' + path + '"] looks for all anchor tags inside of the header block whose end match the path.

This is pure genius.

References: http://docs.jquery.com/Tutorials:Auto-Selecting_Navigation

Did this help you out? It took me a few days to piece together all this information together, I hope this saves you some time (who knows, maybe the future me will be thankful I wrote this down). Let me know your thoughts. shanestillwell@gmail.com