Bootstrap collapse with only one element

I am trying to use Bootstrap collapse components.

This works well, but I noticed that sometimes it does not close all other elements; when I click in order from the first to the third, and then again return to the first, the third remains open.

My markup is the same as the sample code that Bootstrap provides, because right now I'm just testing.

<div class="accordion" id="accordion2"> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne"> Collapsible Group Item #1 </a> </div> <div id="collapseOne" class="accordion-body collapse in"> <div class="accordion-inner"> Part 1 </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo"> Collapsible Group Item #2 </a> </div> <div id="collapseTwo" class="accordion-body collapse"> <div class="accordion-inner"> Part 2 </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseThree"> Collapsible Group Item #3 </a> </div> <div id="collapseThree" class="accordion-body collapse"> <div class="accordion-inner"> Part 3 </div> </div> </div> 

JavaScript Code:

 $(".collapse").collapse("#accordion2"); 

Given that I'm going to use these components in the menu to show that the group is open according to the value of the PHP variable, do I just need to print the class in for div collapseOne / collapseTwo , etc.?

+6
source share
2 answers

You do not need part of javascript, in fact - delete ! It is the code that causes the strange behavior - accordion2 initialized twice, which leads to a double set of "logic". Your problem is fully reproducible using either javascript or not.

As a rule, with regard to tweeter bootstrap, when you can put all your data and binding functions into data attributes , as you did, you will never have to do javascript. TB does the job automatically when the page loads, looking for those data attributes .

Consider javascript as a second option, an alternative way when you cannot do what you want by simply specifying data attributes .

+4
source

If you made your markup according to bootstrap to collapse documents , you can achieve this with the following jQuery code:

 $(document).on('click', '.accordion-toggle', function(e) { event.preventDefault(); $('#accordion2').find('.accordion-body').collapse('hide'); $(this).parent().next().collapse('show'); }); 
+1
source

Source: https://habr.com/ru/post/914437/


All Articles