danielstocks / jQuery-Collapse

A lightweight (~1kb) jQuery plugin that enables expanding and collapsing content
http://webcloud.se/jQuery-Collapse/
MIT License
679 stars 153 forks source link

Nesting collapses #78

Closed SgtOddball closed 4 years ago

SgtOddball commented 9 years ago

There's nothing to say how to nest a collapse within a collapse but I have managed it and so i'm posting the result for those that might be interested (It should in theory be able to work as far down as you feel like but i've only worked to two levels.)

The Html is as follows: -

<div class="Parent">
  <h3>View Parent</h3>
  <div>
    <div class="content">
      <div>
        <span class="rowborders">Something</span>
        <span class="rowborders">&nbsp;</span>
        <span class="rowborders">Something else</span>
      </div>
      <div class="Child">
        <h3>View Child</h3>
        <div>
          <div class="content">
            <div>
              <span class="rowborders">Something</span>
              <span class="rowborders">&nbsp;</span>
              <span class="rowborders">Something else</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

For the javascript call to collapse as follows

var Ph;  //Parent height
var Ch;  //Child height
var P = "div[class='Parent]";  //The outer parent div
var C = "div[class='Child']";  //The outer child div, to add more levels just add further classes

$(P).collapse({
  open: function() {
    Ph=this.children().outerHeight();  //Sets the parent height value. 
    this.addClass("open");  
      this.css({ height: Ph });  //As per usual so far
  },
  close: function() {
    if($(C).children("div").hasClass("open")){
      $(C).trigger("close");  
      /*Runs a check to see if any child collapses are open and closes them 
      This would need to be added any parent of any child if going to further levels.*/
    };
    this.css({ height: 0 });
    this.removeClass("open");
  }
});
$(C).collapse({
  open: function() {
    Ch=this.children().outerHeight();  //this time we get the child height
    this.addClass("open");  
    this.css({ height: Ch });
    $(P).children("div").css({ height: (Ch+Ph) });  /*Calls changes the parent height to include 
    the childs height, note the ("div") in the children tag, this needs to be the same as the 
    parent element otherwise it gets applied to any element directly inside the parent, such 
    as the h3 tag.*/
  },
  close: function() {
    this.css({ height: 0 });
    this.removeClass("open");
    $(P).children("div").css({ height: Ph });  /*Sets the parents height back to what it was 
    before. */
  }
});

Hope that makes sense and should be of some use to anyone trying to nest the collapses within themselves.

danielstocks commented 4 years ago

Thanks for the tip, I might add an example on the page.