Bootstrap collapse - opening multiple accordions at the same time

1.4k Views Asked by At

I've got to a point where my accordions open up at the same time - see http://www.bootply.com/Go4t29rYyF

When you click on "tab1" all the "tab1s" open, when you click on "tab2" all the "tab2s" open - great! But I cant open "tab1s & tab2s" at the same time, it only works when I close one of the tabs first before opening another. The issue is with my js but cant work it out.

$(function () {

        var $active = true;

        $('.panel-title > a').click(function (e) {
            e.preventDefault();
        });

        $('.number1-collapse').on('click', function () {
            if (!$active) {
                $active = true;
                $('.panel-title > a').attr('data-toggle', 'collapse');
                $('.number1').collapse('hide');
            } else {
                $active = false;
                $('.number1').collapse('show');
                $('.panel-title > a').attr('data-toggle', '');
            }
        });


        $('.number2-collapse').on('click', function () {
            if (!$active) {
                $active = true;
                $('.panel-title > a').attr('data-toggle', 'collapse');
                $('.number2').collapse('hide');
            } else {
                $active = false;
                $('.number2').collapse('show');
                $('.panel-title > a').attr('data-toggle', '');
            }
        });
    });
2

There are 2 best solutions below

1
On BEST ANSWER

I've tidied up your code and changed to using the toggle method instead of having various flags. The problem is that you are sharing the active flag between them. Here is the improved code and Bootply:

$(function () {
    $('.panel-title > a').click(function (e) {
        e.preventDefault();
    });

    $('.number1-collapse').on('click', function () {
        $('.number1').collapse('toggle');
    });

    $('.number2-collapse').on('click', function () {
        $('.number2').collapse('toggle');
    });
});
0
On

You may want to specify which elements you are effecting in your function using the event parameter

Example:

   $('.number2-collapse').on('click', function (event) {
        var panelTitle = $(event.currentTarget).find('.panel-title > a');
        var number = $(event.currentTarget).find('.number2');
        if (!$active) {
            $active = true;
            $(panelTitle).attr('data-toggle', 'collapse');
            $(number).collapse('hide');
        } else {
            $active = false;
            $(number).collapse('show');
            $(panelTitle).attr('data-toggle', '');
        }
    });

This is an example. You may need to alter this code for it to work in your situation