Search code examples
phpjqueryslidetoggle

expand/collapse div (toggle) when clicking on header


I have the following jQuery code to toggle the view of more information in a div.

$(".expandCollapse").click(function () {
    var bidValue = this.id,
    expandArea = $("#"+bidValue+'_status')
    expandArea.slideToggle(500);
});

The code works to toggle the view of displaying more information when the submission header is clicked. The div IDs of $moreInfo are dynamically created.

$moreInfo = $bidValue.''."_status";

echo "<div class='expandCollapse' id='$bidValue'>Submission</div>";

echo "<div id='$moreInfo'>$displayComments</div>";

However I want to open only one view/div at a time. If a div is open when a submission is clicked it should be closed before the other one is opened.

I've tried several things but it closes or hides all divs. Searching the web only show a solution using anchor tags.

Any thoughts...?

Thanks.


Solution

  • To achieve this you can put a common class on the second div element to allow you to hide them all before showing the next, like this:

    echo '<div id="$moreInfo" class="expand-area">$displayComments</div>';
    
    $(".expandCollapse").click(function () {
        var bidValue = this.id,
        expandArea = $("#" + bidValue + '_status').slideToggle(500)
        $('.expand-area').not(expandArea).hide();
    });
    

    Also note that you can make your code much more simple and generic by usnig DOM traversal to select the elements, instead of building selector strings based on related id attributes, like this:

    $(".expandCollapse").click(function () {
        var expandArea = $(this).next('.expand-area').slideToggle(500);
        $('.expand-area').not(expandArea).hide();
    });
    

    The code above assumes that the elements are siblings, but you can easily amend the next() to traverse however is required.