John_Cartor
John_Cartor

Reputation: 15

add active class in tab dynamically ajax and jQuery

I am trying to make ajax based tabs, actually, I am trying to load in the tab's particular div. to do I have to add a dynamically active class to understand which tab is currently open. this is the same as the bootstrap tab difference here is it is div load-based tab active.

I read all other threads but all was not helpful for me, I created a function that loads the data and helping to append in tab div it working but I am not able to add and remove the active class in li and divs.

Please help me, How I achieve it, When clicking on li it will add class active and it div too. Please help me,

$(function() {
  $("ul#myTab>li>a.custLink_tabs").click(function(e) {
    pageurl = $(this).attr("dataLanding-target");
    landingtab = $(this).attr("data-landing");
    $("ul#myTab")
      .find('a[dataLanding-target="' + pageurl + '"]')
      .parent()
      .addClass("active");
    $.ajax({
      cache: false,
      url: pageurl,
      success: function(data) {
        $("div#" + landingtab).html(data);
      },
      error: function(jqHXR, textStatus) {
        if (textStatus === "timeout") {
          alert("ERROR");
        }
      },
      timeout: 10000,
    });
    return false;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tabbable">
  <ul class="nav nav-tabs" id="myTab">
    <li class="active">
      <a class="custLink_tabs" datalanding-target="./pages1.php" data-landing="tua-tab-1">TAB 1</a>
    </li>

    <li>
      <a class="custLink_tabs" datalanding-target="./pages2.php" data-landing="tip-tab-2">TAB 2</a>
    </li>
  </ul>
  <div class="tab-content">
    <div id="tua-tab-1" class="tab-pane fade active in">
    </div>

    <div id="tip-tab-2" class="tab-pane fade"></div>
  </div>
</div>

Upvotes: 0

Views: 794

Answers (1)

partik
partik

Reputation: 23

I think you can modify your code, just add

  $(".custLink_tabs")
  .removeClass("active");

just remove all the instances of active classes and then add active class to the current tab you want.

Good luck :)

Upvotes: 0

Related Questions