Link outside nav-tabs to activate a tab-panel/tab-content using Bootstrap 5. Basically, how can I simplify t" /> Link outside nav-tabs to activate a tab-panel/tab-content using Bootstrap 5. Basically, how can I simplify t" /> Link outside nav-tabs to activate a tab-panel/tab-content using Bootstrap 5. Basically, how can I simplify t"/>

Show tab-pane from a outside link click

65 Views Asked by At

I need a <a href="#" class="link-one">Link</a> outside nav-tabs to activate a tab-panel/tab-content using Bootstrap 5.

Basically, how can I simplify this?

// show relevant Bootstrap tab from a outside link click

$('.link-one').on('click', function(){
  $('#tab-one-pane').addClass('show active');
  $('#tab-two-pane').removeClass('show active');
  $('#tab-two').removeClass('active');
  $('#tab-one').addClass('active');
});

$('.link-two').on('click', function(){
  $('#tab-two-pane').addClass('show active');
  $('#tab-one-pane').removeClass('show active');
  $('#tab-one').removeClass('active');
  $('#tab-two').addClass('active');
});

Thank you in advance.

1

There are 1 best solutions below

0
berkobienb On

Add a class called link to your anchor tags making the data-target attribute your unique IDs

HTML:

<a href="#" class="link" data-target="#tab-one">Link to Tab One</a>
<a href="#" class="link" data-target="#tab-two">Link to Tab Two</a>

JS:

   $('.link').on('click', function(e) {
      let target = $(this).data('target');
      $('.nav-tabs a[href="' + target + '"]').tab('show');
    });

This will solve the repeating code.