atleast one active class when dynamic tabs are removed inside div


I'll try to be specific as possible. I have a navbar which can have dynamically added tabs, upon clicking for additional tab, these additional tabs can also be removed by clicking on close button. Here's the Html:

<ul id="nav-tabs" data-tabs="tabs" >
 <li id="test"  class="active">
  <a href="#home" data-toggle="tabs" >
   <img src="assets/img/button_home_selected3.png" class="hover" width="83" />
    <span>Home<button type="button" class="close">&times;</button></span>

The li tags are dynamically added and removed, the active class in li tag shows different images making the tabs differentiable, thus the active class toggles between the li tags.

To close the tabs the script is:

$('.close').click(function(e) {
 var panelId = $(this).closest("li").remove().attr("aria-controls");
 $("#tab" + panelId).remove();

I just want atleast one active tab even when the active tab is removed by the user. Currently, when i close the active tab, there is no active class, making the tabs similar.

Problem courtesy of: Hunain


When you close the tab, take the index of the tab. If it's the last one, then add the active class to the last tab, if first, then first, if is somewhere in the middle, then take the one from the left or from the right of the closed tab.

$(".close").on("click", function() {
      var elem = $(this).closest("li");

      if (elem.hasClass("active")) {
          var idx = elem.index(),
              remainingTabs = $("li");

          if (idx <= remainingTabs.length) {
              $(remainingTabs.get(idx - 1)).addClass("active");
          } else if (idx == 0) {

      // remove current tab
      $(".close", elem).unbind();
Solution courtesy of: TheBrain


You can try this:

$('.close').click(function(e) {
    var panelId = $(this).closest("li").remove().attr("aria-controls");
    $("#tab" + panelId).remove();

Replace the .last() with .first(), if you want the first tab to be active. :)

Discussion courtesy of: Praveen Kumar

This recipe can be found in it's original form on Stack Over Flow.