Aries Azad
Aries Azad

Reputation: 356

Only expand one bootstrap 4 collapse at a time

I have this HTML where it is going to have multiple Bootstrap 4 collapse cards. I need for it to only open one at a time and if another is opened all sibling cards collapse must hide. Please look at my codepen.

https://codepen.io/sazad/pen/XPWXYR

The function I am trying to write I am not sure why it is not rendering anywhere. Right now it is just a console.log but Please guide me in the right direction of making this possible.

Please view codepen to see the HTML working with the JQuery.

function expandOneOnly() {
 if ($(".panel").find(".collapse").hasClass("show")) {
     console.log("hi");
 }

function enableNotification() {
$('.notify-check').change(function() {
    $(this).closest('.panel').find(".caret-icon").toggleClass("hide");
    $(this).closest('.panel').find(".disabled-overlay").toggleClass("hide");
    $(this).closest('.panel').find(".select-text-display").toggleClass("hide");
    if ($(this).closest('.panel').find(".collapse").hasClass("show")) {
        $(this).closest('.panel').find(".collapse").toggleClass("show");
        $(this).closest('.panel').find(".caret-icon").toggleClass('fa-caret-up fa-caret-down');
    }
     expandOneOnly();
});
}

$(document).ready(function() {
overlayWidth();
enableNotification();
expandSelection();
frequencySelection();  
});

Upvotes: 0

Views: 476

Answers (2)

Aries Azad
Aries Azad

Reputation: 356

The answer below worked out pretty well.

function expandSelection() {
$(".btn-title").click(function() {
    $(this).find(".caret-icon").toggleClass("fa-caret-up fa-caret-down");
    if ($(this).closest(".panel").siblings().find(".collapse").hasClass("show")) {
        $(this).closest(".panel").siblings().find(".collapse").removeClass("show");
        $(this).closest(".panel").siblings().find(".caret-icon").toggleClass("fa-caret-up fa-caret-down");
    }
});
}

Check out updated Codepen for full HTML, CSS, JQuery code: https://codepen.io/sazad/pen/XPWXYR

Thanks everyone!

Upvotes: 0

Akrion
Akrion

Reputation: 18515

I think you can simplify this so that the handler only has:

function enableNotification() {
    $('.notify-check').change(function() {
        var panel = $(this).closest('.panel')
        $(this).closest('.row').children().removeClass('active')
        panel.addClass('active')
     });
}

and then you have this in your CSS:

.active .disabled-overlay {
  display: none;
}

.active .caret-icon,
.active .select-text-display,
.active .collapse {
  display: inherit;
}

This way you only handle the current item and add active class and for all others you simply remove that class. The CSS takes care of the rest.

Here is this working

Upvotes: 1

Related Questions