1

I'm trying to make a Javascript action when a bootstrap tab is opened. I can't get it to work. These are the scripts I've tried:

$('.nav-tabs a').on('shown.bs.tab', function(){
    vchart.redraw();
});

And

$(document).ready(function(){
    $(".nav-tabs a").click(function(){
        $(this).tab('show');
    });
    $('.nav-tabs a').on('shown.bs.tab', function(){
        vchart.redraw();
    });
});

I have these scripts inside of the tabs themselves. I also tried:

$('ul.nav a').on('shown.bs.tab', function (e) {

instead of

$('.nav-tabs a').on('shown.bs.tab', function(){

Some HTML

<div class="col-md-9">
  <ul class="nav nav-tabs">
    <li class="active">
      <a data-toggle="tab" href="#1">Tab 1</a>
    </li>
    <li>
      <a data-toggle="tab" href="#2">Tab 2</a>
    </li>
  </ul>
</div>

<div id="1" class="tab-pane fade in active">
  Tab 1 content...
</div>
<div id="2" class="tab-pane">
  Tab 2 content...
</div>

What is going on?

Nour
  • 143
  • 1
  • 15

1 Answers1

1

You have to bind the event (addEventListener in terms of vanilla js)

$('ul.nav a').bind('click', function() { //bind whatever event you want 
  alert('User clicked on "foo."');
  //vchart.redraw();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-9">
  <ul class="nav nav-tabs">
    <li class="active">
      <a data-toggle="tab" href="#1">Tab 1</a>
    </li>
    <li>
      <a data-toggle="tab" href="#2">Tab 2</a>
    </li>
  </ul>
</div>

<div id="1" class="tab-pane fade in active">
  Tab 1 content...
</div>
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
  • This did the trick. Thanks for the help. I didn't know I had to use addEventListener. – Nour Jan 20 '19 at 02:42
  • Can you tell me if I can load a
    with specific id when a tab is opened, with part of the script above?
    – Nour Jan 20 '19 at 03:16
  • Yes, but only if a specific tab is opened. I am using a javascript chart which must only be loaded when the tab is actually opened. – Nour Jan 20 '19 at 03:23
  • I'm trying to solve a problem with a new approach, yet the redraw function won't do its job for some reason. Do you know any other solutions for this problem? https://stackoverflow.com/questions/54172274/morris-area-chart-in-bootstrap-tab – Nour Jan 20 '19 at 04:02