Loolooii
Loolooii

Reputation: 9170

Control slideToggle() jQuery

I have 4 form_header divs and 4 form_body divs. I'm using jQuery slideToggle() to expand the form_body divs by clicking the form headers.

This is a perfect example of what I'm doing: jQuery collapsible div

This is the code I've used:

<script type="text/javascript">
                $(document).ready(function(){

        $(".form_body").hide();

        $(".form_header").click(function(){
            $(this).next(".form_body").slideToggle(0);
        });
        });
    </script>

What I would like is when I expend one of these divs, and I expand another one the expanded one collapses, so that one can't expand two or more of them at the same time. How can I do that? Thanks for your help.

Upvotes: 1

Views: 549

Answers (2)

James Allardice
James Allardice

Reputation: 165971

As has already been noted it may be easier to use a plugin for this, but alternatively, something like this should do the trick:

$(".form_header").click(function() {
   $(".form_body").not($(this).next()).slideUp();
   $(this).next(".form_body").slideToggle(); 
});

It hides all the other .form_body elements, then toggles the correct one. See an example running here.

Upvotes: 0

andyb
andyb

Reputation: 43823

You might be better off using jQuery UI Accordion. The functionality you are after is already built in.

Upvotes: 2

Related Questions