jQuery slideToggle one div at a time instead of all independently

markratledge picture markratledge · Apr 29, 2011 · Viewed 26.3k times · Source

I'm using the function below that toggles divs, and with it, any one of the entry-content divs can be opened or closed independently of all.

What would be great is if only one entry-content div would be open at any time. Clicking a closed entry-title div would close any other entry-content div and then open the one clicked. I need to stay with the html markup, as it is created dynamically by Wordpress. Is this possible?

Function:

jQuery(document).ready(function($) {
$(".entry-content").hide('slow');
$(".entry-title").click(function() {
$(this).parent().children(".entry-content").slideToggle(500); });
});

html

<div class="entry-post">

   <h2 class="entry-title">Post Title 1</h2>

   <div class="entry-content">Lorem Ipsum...

</div></div>

   <h2 class="entry-title">Post Title 2</h2>

   <div class="entry-content">Lorem Ipsum...

</div></div>

More of the same....

</div>

Answer

Derek picture Derek · Apr 29, 2011

Just close them all up again every time one is clicked:

jQuery(document).ready(function($) {
$(".entry-content").hide('slow');
$(".entry-title").click(function() {
    $(".entry-content").hide();
$(this).parent().children(".entry-content").slideToggle(500); });
});

Example: http://jsfiddle.net/auUxk/