Question

Am using slide toggle to slide down the div it working fine [with the help of stack overflow friends], Now am facing another problem , i want to close the toggled div when i click other div which is also having toggle function.

<div id="click" data-class="slide" class="toggle">Toggle</div>
<div class="slide" id="slide" data-class="slide" style="display:none;">
<p>name 1</p>
<p>name 2</p>
<p>name 3</p>
</div>
<div data-class="slide1" class="toggle">Toggle</div>
<div class="slide1" style="display:none;">
<p>name 1</p>
<p>name 2</p>
<p>name 3</p>
</div>
<div data-class="slide2" class="toggle">Toggle</div>
<div class="slide2" style="display:none;">
<p>name 1</p>
<p>name 2</p>
<p>name 3</p>
</div>


<script>
   $(document).ready(function(){
   $( ".toggle" ).click(function() {
   var tog = $(this).("data-class");
   $("."+tog).slideToggle( "fast", function() {
   });
   });
   });
</script>

For ex : On clicking the div with attribute data-class it toggle the div of respective class name and i am clicking another div it is toggle respective div but i want to toggle up the previous toggled div

Was it helpful?

Solution

Since you will be toggling the div that was previously open, I assume you will only have one div toggled out at any time, you could try something like this:

$(document).ready(function(){
    $( ".toggle" ).click(function() {
        if ($(this).next().is(":visible"))
            $(this).next().slideToggle("fast");
        else {
            $(".toggle").each(function() {
                if ($(this).next().is(":visible"))
                    $(this).next().slideToggle("fast");
            });

            var tog = $(this).attr("data-class");
            $("."+tog).slideToggle("fast");
        }
    });
});

So for everytime you click a div with the "toggle" class, it will iterate through all the other divs with "toggle" class, checking if it is visible, and if it is, then toggle it to close.

EDIT: Made the change to account for clicking an already toggled (shown) div, to close it. There might be a better logic/algorithm way to handle this, but currently it does "if the current list is visible, close it and move one, else if it is an unopened one, toggle the opened one and toggle the one just clicked to show".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top