Reputation: 7035
So I have this WordPess site that has a myriad of custom links in its menu, and I figured it would save me some time to simply set a class active to the current menu item using js instead, and jQuery in particular. Like so -
var url = window.location;
$('a[href*="' + url + '"]', 'header').addClass('active');
Goodbye php overhead!
Using this script I can't seem to set the class when on a single page though, even if the url partly matches a menu item (for example, a category name is in the menu and the url is /thatcategory/somepost/). Is there something that I can add to this script that would run it the same way on all pages?
Upvotes: 0
Views: 216
Reputation: 1437
Make sure your trailing slashes match, so if there is a slash at the end of window.location
, there needs to be one in your href
. It might also help if you check if the links have a full domain in them or not.
http//www.example.com/one/two is not going to match a link with href /one/two
Might be worth looking into using window.location.pathname
and match on that instead of the full URL.
Upvotes: 1