e-Designary e-Designary - 3 months ago 16
jQuery Question

jQuery adding and removing classes dynamically when the user clicked

I've a problem with the following code. I've two tabs in my navigation Tab-1 & Tab-2, when the user click on any tab, then I want to add the active class to it and at the same time I want to remove the active class from previously active tab. Also the tab which is currently active should display its content and have to hide the remaining content. It means when the user clicked on any tab it should display only its content and the other contents should be hidden. Please help me thank you.

<style>
.wrapper .tabs {
display: none;
}
.wrapper .tabs.active {
display: block;
}
</style>




<div class="wrapper">

<!-- Navigation -->
<ul class="nav">
<li class="active"><a href="#tab-1">Tab-1</a></li>
<li><a href="#tab-2">Tab-2</a></li>
</ul>

<!-- Panel-1 -->
<div id="tab-1" class="tabs active">
<p>Tab-1 Content</p>
</div>

<!-- Panel-2 -->
<div id="tab-2" class="tabs">
<p>Tab-2 Content</p>
</div>

</div>




<!-- Script -->
<script>
$(document).ready(function () {
$('.nav li').click(function() {
$('.nav li.active').removeClass('active');
$(this).addClass('active');
});

// To display content for active class only
$('.nav li').click(function() {
$('.wrapper .tabs.active').removeClass('active');
$(this).addClass('active');
});
});
</script>

Answer

You can use .eq(), .index() at click event attached to selector "a[href^='#tab-']" which selects element where href begins with #tab-, create variable referencing elements where id begins with tab-, call event.preventDefault() within click function to prevent navigation to document fragment, .hide(), .show()

   $(document).ready(function() {
     var a = $("a[href^='#tab-']");
     var tabs = $("[id^=tab]");
     a.click(function(e) {
       e.preventDefault();
       tabs.hide().eq(a.index(this)).show()
     })
   })
#tab-1 {
  display: block;
}
[id^="tab"]:not(#tab-1) {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js">
</script>
<div class="wrapper">
  <!-- Navigation -->
  <ul class="nav">
    <li>
      <a href="#tab-1">Tab-1</a>
    </li>
    <li>
      <a href="#tab-2">Tab-2</a>
    </li>
  </ul>
  <!-- Panel-1 -->
  <div id="tab-1" class="tabs active">
    <p>Tab-1 Content</p>
  </div>
  <!-- Panel-2 -->
  <div id="tab-2" class="tabs">
    <p>Tab-2 Content</p>
  </div>
</div>

Comments