symon
symon

Reputation: 650

How can I load a tab via a link on my web application?

thanks for your time firstly.

Problem: I am trying to link to a profile page on my web application from a number of different places, how can I have a button redirect to a certain tab on this page?

  <div class="row">
<div class="col-lg-12">
  <div class="card card-tab">
    <div class="card-header">
      <ul class="nav nav-tabs">
        <li role="tab1" class="active">
          <a href="#tab1" aria-controls="tab1" role="tab" data-toggle="tab">Profile</a>
        </li>
        <li role="tab2">
          <a href="#tab2" aria-controls="tab2" role="tab" data-toggle="tab">Alerts</a>
        </li>
        <li role="tab3">
          <a href="#tab3" aria-controls="tab3" role="tab" data-toggle="tab">Settings</a>
        </li>
        <sec:authorize access="hasRole('ADMIN')">
        <li role="tab4">
          <a href="#tab4" aria-controls="tab4" role="tab" data-toggle="tab">Admin</a>
        </li>
        </sec:authorize>
      </ul>
    </div>

When I click a tab I can see it will be amending the url to /profile#tab1/2/3 etc however linking to that directly just displays the profile page.

https://github.com/symonk/Release-Management/blob/master/Releases/src/main/webapp/WEB-INF/views/profile.jsp

I'm guessing some Javascript will do the trick, but im not really sure where to begin

Upvotes: 0

Views: 113

Answers (1)

Gilles Verstraeten
Gilles Verstraeten

Reputation: 36

I browsed the link you gave, you use Bootstrap for the tabs and I noticed you also use jQuery. A solution for you might be to use anchors in URL and activate the tab based on this. For example if you go to http://sample-env.qp3bsthmnq.eu-west-2.elasticbeanstalk.com/profile#tab3

After having added this in your code :

var loadTab = function() {
    var tabId = location.hash;
    if(tabId !== undefined && $('.nav-tabs a[href="' + tabId + '"]') !== undefined) {
        $('.nav-tabs a[href="' + tabId + '"]').tab('show');
    }
};

$(document).ready(function() {
    loadTab();
});

This must have activated the tab with id #tab3

Upvotes: 1

Related Questions