John R Perry John R Perry - 4 months ago 10
CSS Question

jQuery add class .active on menu within subfolders

I was able to find a solid solution on how to add an 'active' class to menu items based on the url of the page:

jQuery(function(){
var page = window.location.pathname,
find = new RegExp(page == '/' ? window.location.origin + '/?jQuery' : page.replace(/\/jQuery/,''));
jQuery('nav a').each(function(){
if(find.test(this.href.replace(/\/jQuery/,''))){
jQuery(this).addClass('active');
}
});
});


This, however, does not work with links within subfolders and I can't seem to figure out a way to make it work. What am I missing?

Answer

This is what I use and it works for menu items in my subfolders

$(".menu-item").each(function() {
  if (this.href == window.location.href) {
    $(this).addClass("active");
  }
});