How to highlight active menu item for the category of the post?

Hello!

Know of information on this subject fully, but I can't do anything.

The meaning is the following:

URL: www.mysite.ru/category1/post1

Is the menu structure:
<div class="header">
the <ul>
 <li class="class"><a itemprop="url" href="http://mysite.ru/category1">category 1
 </a></li><li class="class"><a itemprop="url" href="http://mysite.ru/category2">category 2</a></li>
</ul>
</div>


How to make sure that you added any class (e.g. active) to li element under the condition that the post be in this category? Tried many solutions and none came up.

Please tell me!
July 8th 19 at 11:19
1 answer
July 8th 19 at 11:21
Solution
Offered in each li-element to add data-attribute data-category,
in which to place the corresponding item category, category1, category2, ...:
the <ul>
 <li class="class" data-category="category1"><a itemprop="url">category 1
 </a></li><li class="class" data-category="category2"><a itemprop="url">category 2</a></li>
 </ul>

Next, find the menu items:
var menuLinks = $('.class');
To from url www.mysite.ru/category1/post1 to take the category name, you can:
var activeCategory = window.location.pathname.split('/')[1];

Further, to highlight the desired item, you can:
menuLinks.removeClass('active'); // to clear the selection from all items
menuLinks.filter('[data-category="' + activeCategory + '"]').addClass('active');
You are a genius! Thank you very much! - Lacey.Torphy14 commented on July 8th 19 at 11:24

Find more questions by tags JavaScriptjQuery