Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap 3 jquery event for active tab change

I spent an unrealistic amount of time trying to fire a function when the tab changes of the bootstrap 3 tab/navbar and literally all suggestions google spat out were wrong/did not work.

How to go about this?

Meta-edit: see comment

like image 572
Gerben Rampaart Avatar asked Dec 20 '13 14:12

Gerben Rampaart


People also ask

How do you make a bootstrap tab active using jquery?

$(document). ready(function(){ activaTab('aaa'); }); function activaTab(tab){ $('. tab-pane a[href="#' + tab + '"]'). tab('show'); };

How do you keep the current tab active on page reload in Bootstrap 3?

Answer: Use the HTML5 localStorage Object In Bootstrap, if you refresh the page the tab is reset to default setting. However, you can use the HTML5 localStorage object to save some parameter for the current tab locally in the browser and get it back to make the last active tab selected on page reload.

How do I know which tab is selected in jquery?

var selectedTab = $("#TabList"). tabs(). data("selected. tabs");


2 Answers

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {   var target = $(e.target).attr("href") // activated tab   alert(target); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>  <ul id="myTab" class="nav nav-tabs">   <li class="active"><a href="#home" data-toggle="tab">Home</a></li>   <li class=""><a href="#profile" data-toggle="tab">Profile</a></li> </ul> <div id="myTabContent" class="tab-content">   <div class="tab-pane fade active in" id="home">     home tab!   </div>   <div class="tab-pane fade" id="profile">     profile tab!   </div> </div>
like image 50
Gerben Rampaart Avatar answered Sep 20 '22 12:09

Gerben Rampaart


$(function () {     $('#myTab a:last').tab('show'); });  $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {     var target = $(e.target).attr("href");     if ((target == '#messages')) {         alert('ok');     } else {         alert('not ok');     } }); 

the problem is that attr('href') is never empty.

Or to compare the #id = "#some value" and then call the ajax.

like image 28
Florin Avatar answered Sep 21 '22 12:09

Florin