Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter Bootstrap - Perform action on tab "shown" event

I need to "reset" some page information based on the selected tab in a bootstrap jQuery tab section.

The docs show this event, which is exactly what I need: http://twitter.github.com/bootstrap/javascript.html#tabs

$('a[data-toggle="tab"]').on('shown', function (e) {
  e.target // activated tab
  e.relatedTarget // previous tab
})

I need to get the 'href' attribute of the e.Target and e.relatedTarget, which uniquely identify those 2 tabs and the 2 tab-content panes they are linked to.

Here's my problem: the e object is some object that I'm not expecting or used to. I can't use any of the jQuery methods like e.target.attr('href') -- all the normal jquery methods I'm used to are gone. I tried accessing it like a raw object attribute -- e.href , and got https://127.0.0.1/test?action=view#tab-a" not #tab-a

I can code a workaround with this - but I'm clearly doing something wrong. There should be an easy way to directly get #tab-a from e.target -- but I can't figure it out.

like image 300
Jonathan Vanasco Avatar asked Oct 31 '12 18:10

Jonathan Vanasco


3 Answers

Try $(e.target).attr('href') instead.

like image 70
Sara Avatar answered Oct 29 '22 23:10

Sara


Late to the party by here is my take:

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {

    e.currentTarget ...

});

e.currentTarget is the current anchor just clicked

like image 40
TheSoul Avatar answered Oct 29 '22 22:10

TheSoul


If someone needs to know which tab index is currently selected without manually count it in DOM.

Use case: when #hrefs are updated dynamically and you can relay on tab index.

jQuery function .index() returns integer indicating the position of the first element within the jQuery object relative to its sibling elements.

var el = jQuery('#some .thing'); // some DOM node that contains tab html structure
var tab_list = el.find('.tabbable').first().find('a[data-toggle="tab"]');
// event namespace ".bs.tab" is important in some versions of Bootstrap 
tab_list.on('shown.bs.tab', function(e){

    // zero based index
    // jQuery function `.index()` returns zero-based DOM "order" index
    tab_index = $(e.target).parent().index();

    // store this index to cookie or somwhere
    // so that you can show that tab again when user comes back to page
    // or makes a page refresh (F5)
});
like image 38
hrvoj3e Avatar answered Oct 29 '22 23:10

hrvoj3e