WellNo WellNo - 2 months ago 11
Javascript Question

Jquery, on click on header, open panel body

I have this panel:

<div class="panel">
<div class="panel-heading" style="cursor:pointer"> blablabla
<div class="pull-right"><a href="#" data-perform="panel-collapse"><i class="ti-plus"></i></a> <a href="#" data-perform="panel-dismiss"></a></div>
</div>
<div class="panel-wrapper collapse" aria-expanded="true">
<div class="panel-body">
unicorn
</div>
</div>
</div>





I've wrote this jquery:

<script>
$('.panel').on('click', function() {
$(this).children().toggleClass('panel-wrapper collapse, panel-wrapper collapse in');
});
</script>


But this close the panel, no matter where I'm clicking it. Now I only want that the panel opens, if I click on the panel-heading. ( The whole panel heading, currently the panel only opens if I click on that small
<i> icon
)

and If I click the panel again, it should get closed again.

<div class="panel-wrapper collapse **in**">
would be a closed panel. Without the
in
in collapse in, the panel is closed.

I hope somebody can help me there. And I'm sorry for my bad english.

Thanks for any help :)

Answer

You should use next()

$('.panel-heading').on('click', function() {
        $(this).next('.panel-wrapper').toggleClass(' in');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="panel">
        <div class="panel-heading" style="cursor:pointer"> blablabla
            <div class="pull-right"><a href="#" data-perform="panel-collapse"><i class="ti-plus"></i></a> <a href="#" data-perform="panel-dismiss"></a></div>
        </div>
        <div class="panel-wrapper collapse" aria-expanded="true">
            <div class="panel-body">
                unicorn
            </div>
        </div>
    </div>

You can use slideToggle("slow") to slide in the panel slowly or make use of -webkit transitions in css.

$('.panel-heading').on('click', function() {
        $(this).next('.panel-wrapper').slideToggle("slow");
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="panel">
        <div class="panel-heading" style="cursor:pointer"> blablabla
            <div class="pull-right"><a href="#" data-perform="panel-collapse"><i class="ti-plus"></i></a> <a href="#" data-perform="panel-dismiss"></a></div>
        </div>
        <div class="panel-wrapper collapse" aria-expanded="true">
            <div class="panel-body">
                unicorn
            </div>
        </div>
    </div>

Comments