Search code examples
javascripttwitter-bootstrap-3buttongroup

Change the contents on button tap in button group bootstrap


enter image description here

I want to to change the contents below of button group on tap of every button in button group.

<div class="btn-group btn-group-lg">
<button type="button" class="btn btn-primary segmentedButton ">Section1</button>
<button type="button" class="btn btn-primary segmentedButton active">Section2</button>
<button type="button" class="btn btn-primary segmentedButton">Section3</button>
</div>

I don't want load entire page completely. Just contents below should be changed.

A existing example is http://sourcebits.com/app-development-portfolio/ segmented control. is there any easy way to implement that using html and javascript.


Solution

  • You can create separate div container for each section you have and give it an id attribute. Then, on each button in the button group, you attach an attribute that indicates which div it shall render when the button is clicked.

    Demo (using JQuery):

    $(function() {
    
      $(".btn").on("click", function() {
        //hide all sections
        $(".content-section").hide();
        //show the section depending on which button was clicked
        $("#" + $(this).attr("data-section")).show();
      });
    
    });
    .content-section {
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
    
    <div class="btn-group btn-group-lg">
      <button type="button" data-section="section1" class="btn btn-primary segmentedButton ">Section1</button>
      <button type="button" data-section="section2" class="btn btn-primary segmentedButton">Section2</button>
      <button type="button" data-section="section3" class="btn btn-primary segmentedButton">Section3</button>
    </div>
    
    <div class="content-section" id="section1">
      <h1> Section 1 </h1>
      <p>Section 1 Content goes here</p>
    </div>
    <div class="content-section" id="section2">
      <h1> Section 2 </h1>
      <p>Section 2 Content goes here</p>
    </div>
    <div class="content-section" id="section3">
      <h1> Section 3 </h1>
      <p>Section 3 Content goes here</p>
    </div>