Sunday, 27 November 2016

Making a simple accordion in Bootstrap 3


Creating an accordion for a web site is a breeze with Bootstrap 3. Just including the Bootstrap CSS and Javascript files and jQuery, we can start building an accordion. The accordion is a menu that shows one menu item a time. These menu items are panels and an accordion resembles a tab control with tabs, but is vertically stacked default. The following HTML page renders a simple accordion with Boostrap, CSS, Javascript and HTML.

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">

  <div id="accordion" class="panel-group">
  
   <div class="panel panel-success">
    <div class="panel-heading">
     <h4 class="panel-title"><a href="#collapse1" data-toggle="collapse" data-parent="#accordion">Collapsible panel 1</a></h4>
    </div>
    <div id="collapse1" class="panel-collapse collapse">
     <div class="panel-body"><div class="well">This is a nice collapsible panel.</div><p>This is a test.</p></div>
     <div class="panel-footer">Panel footer</div>
    </div>   
   </div>
   
    <div class="panel panel-warning">
    <div class="panel-heading">
     <h4 class="panel-title"><a href="#collapse2" data-toggle="collapse" data-parent="#accordion">Collapsible panel 2</a></h4>
    </div>
    <div id="collapse2" class="panel-collapse collapse">
     <div class="panel-body">This is another nice panel</div>
     <div class="panel-footer">Hey a panel footer too!</div>
    </div>   
   </div>
   
    <div class="panel panel-default">
    <div class="panel-heading">
     <h4 class="panel-title"><a href="#collapse3" data-toggle="collapse" data-parent="#accordion">Collapsible panel 3</a></h4>
    </div>
    <div id="collapse3" class="panel-collapse collapse">
     <div class="panel-body">Omg a third panel!</div>
     <div class="panel-footer">Let's have another Panel footer too!</div>
    </div>   
   </div>
  
  </div>  
  
</div>

</body>
</html>

Make note that we here use the data-parent HTML5 extension to point to the parent element to get the accordion effect of only showing one panel at a time. Each panel consists of a panel with a panel heading, having a panel title and then a panel body and finally a panel footer. We use the CSS framework of Bootstrap to achieve this.

1 comment: