Search code examples
javascriptjquerytabbed

jQuery multiple toggle buttons with different div ids


I have 4 different divs and 4 buttons, I'm trying to create a tabbed content using jQuery but I can't get it working right. So, I have used data-tab attribute.

jsfiddle.net

jQuery(document).ready(function() {
jQuery('#tabInteract .buttons a').click(function() {
  var index = jQuery(this).index();
  if(jQuery(this).hasClass('active')) {
    jQuery(this).removeClass('active');
     jQuery('#' + jQuery(this).data('tab')).toggleClass(true);
  } else {
      jQuery('#tabInteract .buttons a').removeClass('active');
    jQuery(this).addClass('active')
    jQuery('#' + jQuery(this).data('tab')).toggleClass(true);
  }
})
});

When I click on next button it doesnt close the previous div.


Solution

  • To achieve this behaviour you need to toggle the state of the active button, along with it's related tab, whilst hiding all the other tabs and removing the active class from the other buttons. Try this:

    $('#tabInteract .buttons a').click(function() {
      var $button = $(this).toggleClass('active');
      $('#tabInteract .buttons a').not($button).removeClass('active');
    
      var $tab = $('#' + $(this).data('tab')).toggle();
      $('.closable_box').not($tab).hide();
    })
    a {
      display: inline;
      margin: 5px;
      color: #000;
    }
    a.active {
      color: red;
    }
    .closable_box {
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="tabInteract">
      <div class="buttons">
        <a data-tab="sports" href="#">Button A</a>
        <a data-tab="cars" href="#">Button B</a>
        <a data-tab="fruits" href="#">Button C</a>
        <a data-tab="cats" href="#">Button D</a>
      </div>
    </div>
    
    <div class="closable_box" id="sports">
      Sports
    </div>
    <div class="closable_box" id="cars">
      Cars
    </div>
    <div class="closable_box" id="fruits">
      Fruits
    </div>
    <div class="closable_box" id="cats">
      Cats
    </div>