Dimitri de Ruiter Dimitri de Ruiter - 1 month ago 7
Javascript Question

Bootstrap Nav-tab show hide content

In the app that I am building to learn Rails and JS, I want to use tab-navigation.

This is my tab-navigation pointing to 3 sections. I am now looking to create the JavaScript. How to I approach this when clicking the tabs and set class active to the clicked

<li>
while display the respective section?

I can't do getElementById or so. So, I need something like this structure:

$("li.presentation").on("click", function(event) { ...
$(...).class("active");
$(...).toggle();
};


All help appreciated!

<nav>
<ul class="nav nav-tabs">
<li role="presentation" class="active"><a href="#tab1">Details</a></li>
<% unless @annotation.new_record? %>
<li role="presentation"><a href="#tab2">Tags</a></li>
<li role="presentation"><a href="#tab2">Comments</a></li>
<% end -%>
</ul>
</nav>


Sections

<section id="tab1" class="tab1">
<p>Section 1 content here </p>
</section>
<section id="tab2" class="tab2">
<p>Section 2 content here </p>
</section>
<section id="tab3" class="tab3">
<p>Section 1 content here </p>
</section>
<section id="tab3" class="tab3">
<p>Section 3 content here </p>
</section>


This is my css

.tab1 {
display: block;
}

.tab2 {
display: none;
}

.tab3 {
display: none;
}

Answer

You don't need to use JavaScript and css to accomplish this. You can use the built-in data-toggle="tab" attribute in your tab anchors.

<div class="container">
    <ul class="nav nav-tabs">
      <!-- add data-toggle attribute to the anchors -->
      <li class="active"><a data-toggle="tab" href="#home">Home</a></li>
      <li><a data-toggle="tab" href="#menu1">Menu 1</a></li>
      <li><a data-toggle="tab" href="#menu2">Menu 2</a></li>
    </ul>
      <div class="tab-content">
      <div id="home" class="tab-pane fade in active">
        <h3>HOME</h3>
        <p>Some content.</p>
      </div>
      <div id="menu1" class="tab-pane fade">
        <h3>Menu 1</h3>
        <p>Some content in menu 1.</p>
      </div>
      <div id="menu2" class="tab-pane fade">
        <h3>Menu 2</h3>
        <p>Some content in menu 2.</p>
      </div>
    </div>
</div>

Here is a live demo:
http://www.bootply.com/ZSu8N3bB03