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
2 Answers
Reset to default 2Bootstrap 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'))