Bootstrap Collapse Accordion - Default Expand / Collapse?

I am using Twitter Bootstrap with jQuery.

According to the bootstrap docs, if you want the dumped item to be open by default, you add an extra in class. And if you want the folded element to crash by default, you create a height of up to 0px.

Everything works well and well.

I would like to use Media Query to set the item open by default on large screens, and crashed by default on small screens (and then click to switch both) ...

My HTML:

<div class="accordion" id="accordion1"> <div class="accordion-group"> <div class="accordion-heading"> Heading text. <a class="accordion-toggle" data-toggle="collapse" href="#collapseOne"> (Click to show/hide) </a> </div> <div id="collapseOne" class="accordion-body collapse"> <div class="accordion-inner"> Lorem ipsum. </div> </div> </div> </div> 

My CSS:

 @media (min-width: 768px) { .collapse { height: auto; } } @media (max-width: 767px) { .collapse { height: 0px; } } 

This works fine until you click on it ...

Below 767px, the item is reset by default, and above the item is opened by default. Correctly.

Below 767px you can click to open an item and it opens normally. Click again and he is hiding. Rinse and repeat. Correctly.

Above 767px, when you click to collapse an item, it closes and then opens again. Click it again, and this time it closes and remains closed. Click again and it will open normally. Press again and it closes normally.

So, for some reason, above 767px (when the item is open by default), it takes two clicks to stay minimized without reopening it, and then it works great.

Thoughts?

+7
css twitter-bootstrap media-queries accordion collapse
source share
1 answer

You cannot achieve this type of behavior only with Media Queries, since Twitter Bootstrap Accordion is looking for the .in class to expand / collapse the corresponding .accordion-body .

The option is to determine the width of the window when the page loads, and then add the Bootstrap .collapse() method to show / hide the .accordion-body .

 $(function(){ $(window).resize(function() { // Optional: if you want to detect when the window is resized; processBodies($(window).width()); }); function processBodies(width) { if(width > 768) { $('.accordion-body').collapse('show'); } else { $('.accordion-body').collapse('hide'); } } processBodies($(window).width()); }); 

DEMO: http://jsfiddle.net/grim/z2tNg/

+4
source share

All Articles