javascript - bootstrap accordion - don't collapse if clicking on open panel - Stack Overflow

I have set up bootstrap to hide currently open panels when opening a new panel using:$('.collapse&

I have set up bootstrap to hide currently open panels when opening a new panel using:

$('.collapse').on('show.bs.collapse', function () {
   $('.in').collapse('hide');
});

I would like to extend this so that nothing happens if you click on a currently open panel, i.e. the open panel should stay open when clicking on it. It should only collapse when clicking on other collapsed panels.

I tried it like this, but it doesn't work:

$('.collapse').on('show.bs.collapse', function () {
  $('.in').not(this).collapse('hide');
});

Is this possible somehow?

JSFiddle

I have set up bootstrap to hide currently open panels when opening a new panel using:

$('.collapse').on('show.bs.collapse', function () {
   $('.in').collapse('hide');
});

I would like to extend this so that nothing happens if you click on a currently open panel, i.e. the open panel should stay open when clicking on it. It should only collapse when clicking on other collapsed panels.

I tried it like this, but it doesn't work:

$('.collapse').on('show.bs.collapse', function () {
  $('.in').not(this).collapse('hide');
});

Is this possible somehow?

JSFiddle

Share Improve this question edited Nov 19, 2022 at 13:18 dan1st 16.6k17 gold badges103 silver badges134 bronze badges asked Apr 24, 2017 at 16:03 iamfredrikiamfredrik 3401 gold badge6 silver badges15 bronze badges 2
  • Can you post a plete working example? HTML too. – Carol Skelly Commented Apr 24, 2017 at 16:15
  • I edited my initial post and added a link to a working example on JSFiddle. – iamfredrik Commented Apr 24, 2017 at 18:13
Add a ment  | 

2 Answers 2

Reset to default 2

Bootstrap adds the class 'in' to open panels, you can use that to detect weather the panel is already open, if so then you can skip the collapsing by invoking a event.stopPropagation() you can read more about stopPropagation here.

$('.panel-title > a[data-toggle="collapse"]').click(function(e){
  target = $(this).attr('href')
  if ($(target).hasClass('in')) {
    e.preventDefault(); // to stop the page jump to the anchor target.
    e.stopPropagation()
  }
})

jsfiddle

According to @Sammy answer - for the Bootstrap 4.x you have to change

    if ($(target).hasClass('in'))

to

    if ($(target).hasClass('show'))

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745201003a4616322.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信