For example, I have https://../pc/ and for example there is a category in https://../pc/soft and there is news in these categories https://../pc/0_291q_ob_zor or https://../pc/soft/0-1-test .

How to add an active class to them? That's what i have

 <div id='cssmenu'> <ul> <li><a href='//xxx.xx/'><span>На главную</span></a></li> <li class='active has-sub'><a href='//xxx.xx/pc/'><span>PC</span></a> <ul> <li class='has-sub'><a href='//xxx.xx/pc/soft/'><span>Soft</span></a> <ul> <li><a href='#'><span>...</span></a></li> <li class='last'><a href='#'><span>...</span></a></li> </ul> </li> <li class='has-sub'><a href='//xxx.xx/android/'><span>Android</span></a> <ul> <li><a href='//xxx.xx/android/soft/'><span>Soft</span></a></li> <li class='last'><a href='#'><span>Sub Product</span></a></li> </ul> </li> </ul> </li> </ul> </div> 

There is a script, but it does not work when you go for example to the news, or it does not add to the sub categories AND categories.

 $(function () { $('#cssmenu > ul > li > a').each(function () { var location = window.location.href; var link = this.href; if(location == link) { $(this).closest("li").addClass('active'); } }); }); 

    2 answers 2

     $('#cssmenu a').each(function () { ... $(this).parents("li").addClass('active'); 
    • Everything works except in the news. - Topper-H
    • Explain, please, what it means. - Igor
    • There are news, they are in these categories, and the link looks like this: https://../pc/0_291q_ob_zor , I would like to add to <a href='//xxx.xx/pc/'><span>PC</span></a> active class. - Topper-H
    • $(function() { $('#cssmenu a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active'); }); I found it, but I cannot understand how to integrate it, or how to use it correctly - Topper-H

    Here is the script (jQuery):

     (function( $ ) { $.fn.activeNavigation = function(selector) { var pathname = window.location.pathname var extension_position; var href; var hrefs = [] $(selector).find("a").each(function(){ // Remove href file extension extension_position = $(this).attr("href").lastIndexOf('.'); href = (extension_position >= 0) ? $(this).attr("href").substr(0, extension_position) : $(this).attr("href"); if (pathname.indexOf(href) > -1) { hrefs.push($(this)); } }) if (hrefs.length) { hrefs.sort(function(a,b){ return b.attr("href").length - a.attr("href").length }) hrefs[0].closest('li').addClass("active") } }; })(jQuery); 

    And in the html it is necessary to insert an indication of the active e. (Menu):

     <script type="text/javascript"> $(document).ready(function(){ $(document).activeNavigation("#nav") }); </script> 

    GitHub Solution

    I took it, set it up and everything turned out, it can be useful to someone)