James
James

Reputation: 737

JQuery - change attribute for all similar items in an <UL> list other than active item

My main navigation is a tree-style menu.

Currently, a user must manually expand and collapse each section of the tree, this is achieved in jQuery by adding a has-sub class when collapsed, and menu-expanded class when expanded.

The behaviour I desire however is to force all but the currently expanded item to automatically collapse when a menu item is clicked. I can think of two approaches but I'm not sure how to apply either.

  1. On click assign the active menu item menu-expanded then search all other menu-items with a menu-expanded class and set to has-sub. I don't know how to search by class attribute.
  2. Traverse up and down the tree looking for sibling menu items and setting the style to has-sub for all but the active item.

My code is currently as below, this is for First Child menu items and I have corresponding code for second and third also (I'm getting around to putting it in a loop!).

//First Child List Items
$('#cssmenu > ul > li > ul > li:has(ul)').addClass("has-sub");
$('#cssmenu > ul > li > ul > li > a').click(function() {

    sessionStorage.removeItem('secondChildMenu');

    var parentEl = $(this).parent().parent().parent();
    console.log(parentEl);
    var parentEl = parentEl.children('a').attr('id');   
    console.log(parentEl);
    saveParent(parentEl);


    let firstChildElement = $(this).attr('id');     
    var checkElement = $(this).next();      
    saveFirstChild(firstChildElement);


    $(this).closest('ul > li').addClass('active');  //Add active class

    //Element sub-menu and visible
    if ((checkElement.is('ul')) && (checkElement.is(':visible'))) {

        $(this).closest('li').removeClass('active');                
        checkElement.slideUp(100);                                  
        checkElement.closest('li').addClass("has-sub");
        checkElement.closest('li').removeClass("menu-expanded");    


    }

    //Submenu present and not visible
    if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) {

        checkElement.slideDown(100); //Expand sub-menu
        checkElement.closest('li').removeClass("has-sub");  
        checkElement.closest('li').addClass("menu-expanded");       

    }

    if (checkElement.is('ul')) {
      return false;
    } else {
      return true;
    }
    });

Visual of menu below if it helps.

enter image description here

Upvotes: 1

Views: 45

Answers (1)

Stender
Stender

Reputation: 2492

One way of doing it, could be to find all open menues, and close them, just before you open the menu that you are intending to open.

This could be done the following way.

// find all expanded menues, slide them up, remove the expanded class and add the sub class.

$('li.menu-expanded').slideUp(100).removeClass('menu-expanded').addClass('has-sub');

Upvotes: 1

Related Questions