I\'m using jQuery and I\'m trying to add a class to a menu item based on URL. I tried this(found in other topics), but cannot get it to work properly. It adds the class to every
I'll make a different suggestion. From the examples you have given, it would be very possible to extract the elements class from the URL itself:
var url = window.location.pathname;
var elementName = url.match(/\/(\w+)\.?\/?$/);
$('.nav-' + elementName).addClass('current');
The regular expression matches:
\/
- a slash character (needs to be escaped).(\w+)
- more than one word character. This is also being "captured" and returned.\.?
- a literal dot character (needs to be escaped too). This is to match the begining of a file extension like.php
or .html
. The question mark makes it optional.\/?
- a literal slash character (needs to be escaped too). This is to match a trailing slash for URL's like /members/
. The question mark makes it optional.$
- matches the end of a string.The nav elements full class name is then made up from a concatenation of .nav-
and what ever was matched and captured from the regular expression.
It really depends on the formatting of your URL's but for your example URL's this would work just fine. This code really allows you to by the DRY mindset - Don't Repeat Yourself.