Twitter Bootstrap collapse opened for smartphones

Issue

I have such code snippet:

 <div class="alert alert-info">Today's news
        <div class="pull-right"><a class="btn btn-small" data-toggle="collapse" data-target="#newsDiv"><i class="icon-chevron-down"></i></a></div>
    </div>
    <div id="newsDiv" class="collapse in">
        Today something happened<br>
        Also yesterday happened<br>
        Maybe tomorrow<br>
    </div>

jsFiddle: http://jsfiddle.net/gfUXW/

I want this behaviour: When user visits with phone (width 480 px and below) collapse will be closed, when user visits with a bigger device collapse will be opened autmatically.

To make it responsive I need to do by CSS rules. But I couldn’t figure how can I join responsive classes of bootstrap like “visible-phone” and “collapse in” class.

Solution

Since the collapse is a javascript plugin, I think the answer lies in using some javascript.

If you remove the in class, it will leave your collapse closed by default, which is useful to know. Then you can check this when the document is ready.

  if ($(window).width() > 480) {
    $(".collapse").collapse('show');   
  }

The methods are in the documentation: Bootstrap Collapse

See it in action by clicking run with different screen widths: http://jsfiddle.net/LaAWc/1/

If you want this checked constantly, you’ll have to poll with a timer to keep checking. If that interests you, see How to detect in jquery if screen resolution changes?

Answered By – Alexander Mistakidis

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published