Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Toggle height on multiple sections with one function

I have multiple sections, three to be exact, of varying heights with a basic layout of:

    <section>
       <h2>My heading</h2>
    </section>

I'm looking for a way to show them initially, but then when the user clicks on the <h2>, to have that section decrease to a height of 68px. The main problem is that each section is a different height(i.e the first is 478px, the second 2118px, and the third 247px), but I don't want to write a separate function for each section and was hoping to do it all in one. It was working fine until I closed the first section and instead of re-opening it, click on the second section's <h2>. That's where the problems began. So my question is, is there anyway to do this or do I need a separate function for each section?

sectionSize = "normal";
$(document).ready(function(){
  //var sectionSize = "normal";
  $("h2").click(function(){
     var parentSection = $(this).parents("section");      
    if (sectionSize == "normal") {
      sectionHeight = parentSection.height();
      parentSection.animate({height:"68px"},"fast"),
      sectionSize = "collapsed";
    } else {
      parentSection.animate({height:sectionHeight},"fast"),   
      sectionSize = "normal";
    }
  });
});

I have a fuller version here http://jsfiddle.net/Skooljester/94yqX/ with the HTML and CSS further fleshed out.

like image 893
ayyp Avatar asked May 20 '26 12:05

ayyp


1 Answers

Rather than store the height in a global variable (generally bad to use global variables anyway). Store it against the element using the data() function of jquery:

var parentSection = $(this).parents("section");   
var sectionSize = $(this).data('sectionSize') || "normal";   
if (sectionSize == "normal") {
    $(this).data('sectionHeight' parentSection.height());
    parentSection.animate({height:"68px"},"fast"),
    $(this).data('sectionSize', 'collapsed');
 }
 else {
     parentSection.animate({height:$(this).data('sectionHeight')},"fast"),   
     $(this).data('sectionSize', 'normal');
 }

Updated with full code for click function

like image 78
Richard Dalton Avatar answered May 22 '26 00:05

Richard Dalton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!