Search code examples
jquerythisparent-childparent

Jquery to expand collapse only the div that has been clicked


I have a number of divs on a page that i want to collapse and expand when the user clicks "Expand [+]"

The following code works for one div

<h4 class="expanderHead" style="cursor:pointer;">Contact information <span class="expanderSign">Expand [+]</span></h4>
<div id="profile-section" style="overflow:hidden;">
some stuff
</div>

<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(".expanderHead").click(function(){
    if (jQuery(".expanderSign").text() == "Expand [+]")
    {
    jQuery("#profile-section").removeClass("height-min");
    jQuery("#profile-section").addClass("height-auto");
    }
    else
    {
    jQuery("#profile-section").removeClass("height-auto");
    jQuery("#profile-section").addClass("height-min");
    }

    if (jQuery(".expanderSign").text() == "Expand [+]"){
        jQuery(".expanderSign").text("Collapse [-]");
    }
    else {
        jQuery(".expanderSign").text("Expand [+]");
    }


});
});
</script>

If i then have a number of divs on the page as such

<h4 class="expanderHead" style="cursor:pointer;">Contact information <span class="expanderSign">Expand [+]</span></h4>
<div id="profile-section1" style="overflow:hidden;">
some stuff
</div>

<h4 class="expanderHead" style="cursor:pointer;">Contact information <span class="expanderSign">Expand [+]</span></h4>
<div id="profile-section2" style="overflow:hidden;">
some stuff
</div>

<h4 class="expanderHead" style="cursor:pointer;">Contact information <span class="expanderSign">Expand [+]</span></h4>
<div id="profile-section3" style="overflow:hidden;">
some stuff
</div>

etc....

How can i modify my jquery so that it works for all of these divs individually. i.e it will only minimize or maximize the div that has been clicked?

i've tried a number of different combinations using (this) and parent() and child() but i can't seem to get it right.

Help would be appreciated :)


Solution

  • Thanks for all the suggestions. in the end I went for the Accordion - http://jqueryui.com/accordion/

    Not exactly what i was originally after, but it works well.