Collapse accordions except current, by removing class of each, but this.parent?

846 views Asked by At

So I'm stuck with a plugin that offers a simple accordion, but doesn't offer auto-collapse. I was trying to create a simple script, but I'm not succeeding.

Let me offer some DOM structure:

.mx-groupbox-collapsible.collapsed
  .mx-groupbox-header
  .content
.mx-groupbox-collapsible.collapsed
  .mx-groupbox-header
  .content
.mx-groupbox-collapsible.collapsed
  .mx-groupbox-header
  .content

Assuming the structure speaks for itself, but one thing: when the .collapsed class is removed, it'll expand the item (in my opinion the opposite way of building an accordion..).

Somehow the only way to fire the jQuery script is to target the header ( $('.mx-groupbox-header').click()). What it should do is find each item that does not have a .collapsed class and add it, while removing it from it's parent.

My best guess was this piece of jQuery.

// Target the inner accordion item header
$(".mx-groupbox-header").click(function() { 

  // Target each accordion item that doesn't have class 'collapsed',
  // except the parent of the current clicked item
  $('.mx-groupbox-collapsible').not([$('.collapsed'),$(this).parent()]).each(function(){

      // Add 'collapsed' class, so current opened item, except current will collapse
      $(this).addClass('collapsed');
  });
});

Who can tell me where I'm going wrong and offer me the solution?

1

There are 1 answers

2
Roko C. Buljan On BEST ANSWER

Yes, it's totally inversed than it's usually done...

If that's really your markup you're going to use (click on header and stuff),
you should, on header click - find the .closest() (groupbox parent) like:

// Cache dropdowns
var $collapsible = $('.mx-groupbox-collapsible');


// Target the inner accordion item header
$(".mx-groupbox-header").click(function() { 

  // Find header's collapsible parent
  var $myCollapsible = $(this).closest('.mx-groupbox-collapsible');

  // Target each accordion item that doesn't have class 'collapsed',
  // except the parent of the current clicked item
  $collapsible.not( $myCollapsible ).addClass("collapsed");

  // Eventually (if needed?) do also:
  $myCollapsible.removeClass("collapsed");
});