Yishu Sun Yishu Sun - 7 months ago 24
HTML Question

Responsive webpage accordion in mobile

I almost finish the webpage and I know how to collapse the content, but I still have no idea how to show the content directly, but show them in accordion style in mobile devices without duplicating it.

Here is my code and I use Bootstrap to make accordion.

<div class="container">
<div class="panel-group" id="accordion">
<div class="panel panel-default hidden-xs">
<div class="panel-heading">
<h4 class="panel-title ">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse1" >Collapsible Group 1</a>
</h4>
</div>
<div id="collapse1" class="panel-collapse collapse">
<div class="panel-body">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Collapsible Group 2</a>
</h4>
</div>
<div id="collapse2" class="panel-collapse collapse">
<div class="panel-body">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse3">Collapsible Group 3</a>
</h4>
</div>
<div id="collapse3" class="panel-collapse collapse">
<div class="panel-body">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
</div>
</div>
</div>
</div>

Answer

If you can't duplicate the content and use the bootstrap hidden helper classes, then you could do this with javascript.

First, remove your data attributes that initialize the accordion on all screen sizes.

Second, initialize the accordion based on screen size.

if ($(window).width() < 960) {
  $('#accordion').find('.panel-collapse').addClass('collapse')
  $('#accordion').find('.panel-title a').attr('data-toggle','collapse')
  $('#accordion').collapse()
}
Comments