JQuery - Active Relationship and Kinship

I am working on site navigation and need a guide to dynamically add a class to an active link. Also, as soon as this link is set, and I need to refer to the parent and show it.

This is what I work with. Navigation is an accordion style but does not use the Accordion interface.

<ul id="menu3">
    <li><a href="{site_url}">Home</a></li>
    <li><a class="drop" href="#">Information</a>
        <ul>
            <li><a href="{site_url}information/audio">Audio</a></li>
            <li><a href="{site_url}information/video">Video</a></li>
            <li><a href="{site_url}information/presentations">Presentations</a></li>
        </ul>
    </li>
    <li><a class="drop" href="#">Clinics</a>
        <ul>
            <li><a href="{site_url}clinics/one">Office 1</a></li>
            <li><a href="{site_url}clinics/two">Office 2</a></li>
        </ul>
    </li>
    <li><a href="{site_url}forms/">Forms</a></li>
    <li><a href="{site_url}success_stories/index">Success Stories</a></li>

Then I have a little jQuery to initially hide the submenu items:

$(function(){
$('ul#menu3 ul').hide();                
$('ul#menu3 > li > a.drop').click(function(){
$(this).parent().children('ul').toggle("slow");
   return false;
});

So far so good. Everything is working.

Now I would like to dynamically highlight the active link, and I tried to use:

var path = location.pathname.substring(1);
if ( path )
$('ul#menu3 a[href$="' + path + '"]').attr('class', 'selected');

but that doesn't seem to be enough to add the right class.

, , - . , - , .

. .

+1
1

. "" , . inline. ... comment/ask.

$(function() {
    var pathname = location.pathname;
    var highlight;
    //highlight home
    if(pathname == "/")
        highlight = $('ul#menu3 > li:first > a:first');
    else {
        var path = pathname.substring(1);
        if (path)
            highlight = $('ul#menu3 a[href$="' + path + '"]');
    }
    highlight.attr('class', 'selected');

    // hide 2nd, 3rd, ... level menus
    $('ul#menu3 ul').hide();

    // show child menu on click
    $('ul#menu3 > li > a.drop').click(function() {
        //minor improvement
        $(this).siblings('ul').toggle("slow");
        return false;
    });

    //open to current group (highlighted link) by show all parent ul's
    $('a.selected').parents("ul").show();

    //if you only have a 2 level deep navigation you could
    //use this instead
    //$('a.selected').parents("ul").eq(0).show();
});
+3

Source: https://habr.com/ru/post/1724418/


All Articles