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
.
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.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.