Bootstrap Collapse Accordion - Default Expand/Collapse?

Westyfield2 picture Westyfield2 · Sep 16, 2013 · Viewed 21.2k times · Source

I'm using Twitter Bootstrap, with jQuery.

According to the bootstrap docs, if you want the collapsible element open as default you add the additional class "in". And if you want the collapsible element collapsed as default you style the height to 0px.

That all works well and good.

I would like to use a Media Query to set the element open as default on large screens, and collapsed as default on small screens (and then click to toggle on 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 start clicking it…

Below 767px the element is collapsed as default, and above the element is open as default. Correct.

Below 767px you can click to open the element, and it opens fine. Click again and it hides. Rinse and repeat. Correct.

Above 767px when you click to collapse the element, it closes but then re-opens itself. Click it again and it closes and stays closed this time. Click again and it opens fine. Click again and it closes fine.

So for some reason above 767px (when the element is open as default), it takes two clicks to make it stay collapsed without re-opening itself, and then it works fine.

Thoughts?

Answer

grim picture grim · Oct 9, 2013

You can't achieve this type of behavior only with Media Queries as Twitter Bootstrap's Accordion looks for the .in class in order to expand/collapse the respective .accordion-body.

An option is to detect the window width on page load and then add the use Bootstrap's .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/