Quick help with some jQuery toggle

Posted by mplacona on Stack Overflow See other posts from Stack Overflow or by mplacona
Published on 2010-03-31T09:17:16Z Indexed on 2010/03/31 9:23 UTC
Read the original article Hit count: 394

Filed under:
|

I have the following code:

<script>
    $(document).ready(function() {
        $('.toggle_section').click(function(e){
            parent = $(e.target).closest("div")
            objChild = parent.children('div');
            $('.sectionContentId').hide(400);
            $(objChild).toggle(400);
        });
    });

</script>

<br />
<div class="box" id="parent_section_1">
    <strong>
        <a class="toggle_section" href="javascript:;">New Section 1</a>
    </strong>
    <div class="sectionContentId" id="section_1" style="display: none">
        <br />
        Contents<br />for<br />section<br />1
    </div>
</div>

<br />

<div class="box" id="parent_section_2">
    <strong>
        <a class="toggle_section" href="javascript:;">New Section 2</a>
    </strong>

    <div class="sectionContentId" id="section_2" style="display: none">
        <br />
        Contents<br />for<br />section<br />2
    </div>
</div>

And example can be seen here

As you can see, what I'm trying to accomplish is that when you click on one of the links, all the other "already expanded sections" collapse, and the clicked section expand.

this works fine as it is, but obviously by using the logic:

$('.sectionContentId').hide(400);
$(objChild).toggle(400);

When I click one of the expanded sections in the attempt to close it, it closes briefly and opens again.

I wanna keep the same functionality, but wanna be able to open and close a section by clicking on a link, as well as when I'm opening a section, I wan't it to close everything before opening this new section.

I'm not sure I'm being very clear here, but by looking at the example, you will be able to understand better what I mean.

Thnks in advance

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about jquery-selectors