zigzag
zigzag

Reputation: 67

accordion display to find the next div

Progress: https://jsfiddle.net/zigzag/jstuq9ok/4/

There are probably a few ways to do this but I have a class called sub that I add to hide a 'nested' Div and then use jQuery to toggle the Glyphicon along with display the 'nested' Div. Some asks:

$('.menu-toggle').click(function() {
  $(this).find('span').toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up');
  //How to do something like this to traverse the click and structure $(this).parent.find('.sub:first-child').toggle();
  $('.sub').toggle();
  $('.subsecond').toggle();
});

The nested team structure intended is this:

  1. Adam
  2. Lily

    2.1 Sen

    2.1.1 Tank

    2.2 Another Sen

  3. Justin

What I'm trying to do do is have this traverse through the DOM based on where the click happens to display the sub section under there. I have the content coming from a source system so can't hard code class directly.

Let me know if you have any question.

Upvotes: 0

Views: 172

Answers (1)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

You can find the next div by using .closest('.row') to get the parent .row and .next('.row') to get the next .row of the parent .row if it has class or not using hasClass() so you can use

$('.menu-toggle').click(function(e) {
  e.preventDefault();  // prevent <a> to redirect to the top of the page
  $('.row:not(.sub):not(.subsecond)').not($('.sub').prev('.row')).not($('.subsecond').prev('.row')).not($(this).closest('.row')).find('span.glyphicon-menu-up').toggleClass('glyphicon-menu-down glyphicon-menu-up');
  $(this).find('span').toggleClass('glyphicon-menu-down glyphicon-menu-up');
  var Nextrow = $(this).closest('.row').next('.row');  // get the next row
  if(Nextrow.hasClass('sub')){   // if next row has class sub
    $('.sub').not(Nextrow).hide();  // hide all sub but not this one
    Nextrow.slideToggle(function(){
      if($(this).is(':hidden')){ // check if the .sub is hidden 
        $('.subsecond').hide();  // hide subsecond
        $('span.glyphicon-menu-up').toggleClass('glyphicon-menu-down glyphicon-menu-up');  // toggle arrows to the down
      }
    });      // toggle this sub row
    return false;
  }
  if(Nextrow.hasClass('subsecond')){ // if next row has class subsecond
    $('.subsecond').not(Nextrow).hide(); // hide all subsecond but not this one
    Nextrow.slideToggle();   // toggle this subsecond row
    return false;
  }
});

See Example

Upvotes: 1

Related Questions