Shashank Gaurav Shashank Gaurav - 6 months ago 17
HTML Question

I want to have multiple tabs within single html page but my code isn't working

<ul class="tabs-nav">
<li><a href="#tab-1">Tab1</a></li>
<li><a href="#tab-2">Tab2</a></li>
</ul>
<div class="tabs-stage">
<div id="tab-1">
<p>Tab1 contents</p>
</div>
<div id="tab-2">
<p>Tab2 Contents</p>
</div>
</div>


Above is the html code for multiple tabs (2 here) within my single page. Below is my jquery code.

$('.tabs-stage div:first').show();
$('.tabs-nav li:first').addClass('tab-active');


$('.tabs-nav a').on('click', function(event) {
$('.tabs-nav li').removeClass('tab-active');
$(this).parent().addClass('tab-active');
$('.tabs-stage div').hide();
$(this).show();
});


This is jquery code for switching between multiple tabs within a single page.

Answer

You are showing wrong element. Use $($(this).attr('href')).show(); to show active tab.

$(document).ready(function() {
  $('.tabs-stage div:first').show();
  $('.tabs-nav li:first').addClass('tab-active');


  $('.tabs-nav a').on('click', function(event) {
    event.preventDefault();
    $('.tabs-nav li').removeClass('tab-active');
    $(this).parent().addClass('tab-active');
    $('.tabs-stage div').hide();
    $($(this).attr('href')).show();
  });
});
.tabs-nav li {
  display: inline-block;
  border: 1px solid #ddd;
  border-bottom: 2px solid #ddd;
}
a {
  padding: 3px 10px;
  text-decoration: none;
  color: #455;
}
.tabs-nav li.tab-active {
  border-bottom-color: red;
}
.tabs-stage > div {
  display: none;
  border: 1px solid #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="tabs-nav">
  <li><a href="#tab-1">Tab1</a>
  </li>
  <li><a href="#tab-2">Tab2</a>
  </li>
</ul>
<div class="tabs-stage">
  <div id="tab-1">
    <p>Tab1 contents</p>
  </div>
  <div id="tab-2">
    <p>Tab2 Contents</p>
  </div>
</div>

Comments