Skip to content Skip to sidebar Skip to footer

Capturing 'shown' Event From Bootstrap Tab

I have some 'static' HTML on my page:

Solution 1:

The correct event binding for tab change is shown.bs.tab.

$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
    alert('TAB CHANGED');
})

Update 11-01-2020 --- Bootstrap 4.5

This is still the correct answer however, this is a bit of additional helpful information found all the way at the bottom of the official bootstrap docs page at: https://getbootstrap.com/docs/4.5/components/navs/#tabs

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

You can determine which tab has been selected each time the code fires with e.target.

If you have unique IDs on your elements then you could do something like the following so code only runs when the appropriate tab is clicked.

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
  switch (e.target.id){
      case "mainTab":{
           doMainTabStuff();
           break;
      }
      case "configTab":{
           doConfigTabStuff();
           break;
      }
  }
})

Solution 2:

Use my Nuget package for lazyloading bootstrap tabs here, its very simple, just add "lazyload" class to the "ul" element of bootstrap tabs, then add "data-url" equal to url to load to the any tabs anchor element (a). thats it.

https://www.nuget.org/packages/MT.BootstrapTabsLazyLoader.js/


Solution 3:

'show' and 'shown' events didn't work for me. My solution is not exactly specifically OP's situation, but the general concepts are there.

I had the same issue with bootstrap forcing its own onclick events on tabs (menu buttons and content panels). I wanted to lazy load stuff into a panel depending on what menu button was clicked, and some buttons show a panel on the current page, others were to load a page into an iframe.

At first, I stuffed data into a hidden form field tag, which was the same issue. The trick is to detect some sort of change and act on that. I solved the problem by forcing a change and using an alternate event listening on the buttons without having to touch bootstrap.

1) stash iframe target in button as data attribute:

$('#btn_for_iframe').attr('data-url',iframeurl);

2) bind alternate event onto fire off thingy, and inside, swap out the iframe source

$('#btn_for_iframe').on('mouseup',function(){
   console.log(this+' was activated');
   $('#iframe').attr('src',$('#btn_for_iframe').attr('data-url'));
});

3) force 'change' event on panel shows, then load iframe src

$('#iframe_panel_wrapper').show().trigger('change');

or you can put the change trigger in the mouseup above.


Post a Comment for "Capturing 'shown' Event From Bootstrap Tab"