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


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

The meaning is the following:


Is the menu structure:
<div class="header">
the <ul>
 <li class="class"><a itemprop="url" href="">category 1
 </a></li><li class="class"><a itemprop="url" href="">category 2</a></li>

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
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>

Next, find the menu items:
var menuLinks = $('.class');
To from url 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