Reputation: 3566
I am trying to make accordion with Bootstrap Collapse
. I have this HTML
:
<ul id="ul">
<li>
<div class="first">
<button>
<i class="fa fa-caret-down" aria-hidden="true"></i>
</button>
<a href="#">Name</a>
</div>
<ul class="collapse">
<li>
<a href="#">item 1</a>
</li>
<li>
<a href="#">item 2</a>
</li>
</ul>
</li>
</ul>
When I click on #ul > li
, it must show ul.collapse
.
I am using this JS
:
$('#ul > li').on('click', function (e) {
$('.collapse.in').collapse('hide');
$(this).find('.collapse').collapse();
});
, but it works only first 2 clicks for open and close and after that, it doesn't work. I need to do this with JS
.
Upvotes: 1
Views: 1307
Reputation: 11342
Option 1: You can use slideToggle()
from jQuery.
$('#ul > li').on('click', function(e) {
$(this).find('.collapse').slideToggle();
});
.collapse {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ul">
<li>
<div class="first">
<button>
<i class="fa fa-caret-down" aria-hidden="true"></i>
</button>
<a href="#">Ресторант Топ Мания</a>
</div>
<ul class="collapse">
<li>
<a href="#">Обедно меню</a>
</li>
<li>
<a href="#">Вечерно меню</a>
</li>
</ul>
</li>
</ul>
Option 2: use collapse('hide')
and collapse('show');
$('#ul > li').on('click', function(e) {
$('.collapse.in').collapse('hide');
$(this).find('.collapse').collapse('show');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<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>
<ul id="ul">
<li>
<div class="first">
<button>
<i class="fa fa-caret-down" aria-hidden="true"></i>
</button>
<a href="#">Ресторант Топ Мания</a>
</div>
<ul class="collapse">
<li>
<a href="#">Обедно меню</a>
</li>
<li>
<a href="#">Вечерно меню</a>
</li>
</ul>
</li>
</ul>
Upvotes: 1
Reputation: 686
Try that
$('#ul > li').on('click', function (e) {
if($('.collapse').hasClass('in')) {
$('.collapse.in').collapse('hide');
} else {
$(this).find('.collapse').collapse('show');
}
});
it can be written in better form but that will fix your issue.
Upvotes: 1