Eniss Eniss - 10 days ago 6
jQuery Question

Best way to use bootstrap tabs with their contents

I am trying to create a navigation bar with their contents when clicking. My code looks like lame. Is there a way to shorter my code?

E.g: When Rooms clicked, JQuery adds

active
class to
#nav-hotel
, and removes
active
class from other
li
elements. It also sets
visibility
and
display
of both itself and others.

HTML:

<ul class="nav nav-tabs">
<li id="nav-hotel" role="presentation"><a href="#tab-hotel">Rooms</a></li>
<li id="nav-flight" role="presentation"><a href="#tab-flight">Flights</a></li>
<li id="nav-restaurant" role="presentation"><a href="#tab-restaurant">Restaurants</a></li>
</ul>
<div class="tab-content">
<div id="tab-hotel">hotel</div>
<div id="tab-flight">flight</div>
<div id="tab-restaurant">restaurant</div>
</div>


JQuery:

$("#nav-hotel").click(function () {
$("#nav-hotel").toggleClass("active");
$("#tab-hotel").css("display", "block");
$("#tab-hotel").css("visibility", "visible");
$("#nav-flight").removeClass("active");
$("#tab-flight").css("display", "none");
$("#tab-flight").css("visibility", "hidden");
$("#nav-restaurant").removeClass("active");
$("#tab-restaurant").css("display", "none");
$("#tab-restaurant").css("visibility", "hidden");
});
$("#nav-flight").click(function () {
$("#nav-flight").toggleClass("active");
$("#tab-flight").css("display", "block");
$("#tab-flight").css("visibility", "visible");
$("#nav-hotel").removeClass("active");
$("#tab-hotel").css("display", "none");
$("#tab-hotel").css("visibility", "hidden");
$("#nav-restaurant").removeClass("active");
$("#tab-restaurant").css("display", "none");
$("#tab-restaurant").css("visibility", "hidden");
});
$("#nav-restaurant").click(function () {
$("#nav-restaurant").toggleClass("active");
$("#tab-restaurant").css("display", "block");
$("#tab-restaurant").css("visibility", "visible");
$("#nav-flight").removeClass("active");
$("#tab-flight").css("display", "none");
$("#tab-flight").css("visibility", "hidden");
$("#nav-hotel").removeClass("active");
$("#tab-hotel").css("display", "none");
$("#tab-hotel").css("visibility", "hidden");
});

Answer

Have you tried using data-toggle="tab"? I recently created a similar example with no javascript by including bootstrap.min.js, jquery.min.js and bootstrap.min.css and marking the tabs.

First, mark your "a" items with data-toggle="tab"

 <li id="nav-hotel" role="presentation">
   <a href="#tab-hotel" data-toggle="tab">Rooms</a>
 </li>

Second,mark you div content items with class="tab-pane"

<div id="tab-hotel" class="tab-pane">hotel</div>

Finally, to add a default enabled tab add the active class to one of your divs

<div id="tab-hotel" class="tab-pane active">hotel</div>