Alejandro Montenegro
Alejandro Montenegro

Reputation: 43

reloading current active tab in twitter bootstrap

I was following this recommendation about how to be able to reload current active tab by using:

$('#tab-loaded-content').load($('li.active a[data-toggle="tab"]').attr('href'));

But when I tried this the result was that it loads the initially active tab (the one defined in my html as active) and not the current active tab. So I'm looking for some help to figure out how to do this.

Here is a simplified version of my issue:

<!DOCTYPE html>
  <html>
    <head>
      <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet">
    </head>
  <body>
    <div class="tabbable">      
      <ul id="mainTabs" class="nav nav-tabs">
        <li class="active"><a href="#tabWelcome" data-toggle="tab">Home</a></li>
        <li><a href="#tabProject" data-toggle="tab">Project</a></li>
        <li><a href="#tabEmail" data-toggle="tab">Invite Friends</a></li>
        <li><a href="#tabProfile" data-toggle="tab">My Profile</a></li>
      </ul>
      <div class="tab-content">
        <div class="tab-pane active" id="tabWelcome">
          welcome
        </div>
        <div class="tab-pane" id="tabProject">
          project
        <button id="button" class="btn">Create Project</button>
      </div>
      <div class="tab-pane" id="tabEmail">
        email
      </div>
        <div class="tab-pane" id="tabProfile">
          profile
        </div>
      </div>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/js/bootstrap.min.js"></script>
<script>
    document.getElementById("button").addEventListener("click", function() {
        $('#mainTabs').load($('li.active a[data-toggle="tab"]').attr('href'));
    }, false);
</script>
</body>
</html>

The idea is when clicking on the "project" button on the second tab it should reload that tab, but it reloads the "welcome" tab.

Any advice appreciated!

Upvotes: 4

Views: 12929

Answers (1)

cognant
cognant

Reputation: 441

I had to implement a very similar functionality.

Basically you need to get hold of the current tab 'deactivate' and show it again.

$(document).on('click', '#refresh', function () {
    var $link = $('li.active a[data-toggle="tab"]');
    $link.parent().removeClass('active');
    var tabLink = $link.attr('href');
    $('#mainTabs a[href="' + tabLink + '"]').tab('show');
});

See my jsFiddle for a working demo.

Notice the demo is using Bootstrap 3 hence the use of the shown.bs.tab event to show the time at tab load.

Upvotes: 6

Related Questions