Reputation: 2614
I have a simple bootstrap navigation with two tabs, which is marked up as shown below.
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#sectionA">Section A</a></li>
<li><a data-toggle="tab" href="#sectionB">Section B</a></li>
</ul>
<div class="tab-content">
<div id="sectionA" class="tab-pane fade in active">
<p>Section A content…</p>
</div>
<div id="sectionB" class="tab-pane fade">
<p>Section B content…</p>
</div>
</div>
What I would like is to have deep links for each of the tabs. So instead of #sectionA and #sectionB, I want example.com/contentA and example.com/contentB.
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="example.com/contentA">Content A</a></li>
<li><a data-toggle="tab" href="example.com/contentB">Content B</a></li>
</ul>
<div class="tab-content">
<div id="contentA" class="tab-pane fade in active">
<p>ContentA content…</p>
</div>
<div id="contentB" class="tab-pane fade">
<p>ContentB content…</p>
</div>
</div>
This is all to provide deep links for the search engine crawlers. I will then use javascript to handle user clicks. Something like:
$('a').on("click", function (e) {
var href = $(this).attr("href");
history.pushState(null, null, href);
// Show clicked tab here + associated content
$('do something to show clicked tab here')...
e.preventDefault();
});
As I will need to switch to both the correct tab and content in my javascript snippet, how will this code look?
Upvotes: 3
Views: 3027
Reputation: 1
I've been working on a similar issue, but also wanted the page to jump to the loacation of the tabs, allowing an offset for the top menu bar. This is the script that finally worked for me:
<script>
$(document).ready(() => {
var url = window.location.href;
if (url.indexOf("#") > 0){
var activeTab = url.substring(url.indexOf("#") + 1);
$('.nav[role="tablist"] a[href="#'+activeTab+'"]').tab('show');
var position = $("#tab-options").offset().top -57;
$("html, body").animate({
scrollTop: position
}, 1000);
}
});
</script>
Upvotes: 0
Reputation: 2614
I found a way to solve this. The trick is to first show the tab I want, remove any active tab pane, and then set the clicked tab pane as active.
$('a').on("click", function (e) {
var href = $(this).attr("href");
history.pushState(null, null, href);
var showForId = $(this).prop('id');
$('a[id="' + showForId + '"').tab('show');
$('.tab-pane').removeClass('active');
$('.tab-pane[id="' + showForId + '"]').addClass('active');
e.preventDefault();
});
This worked, and I can now use deep links like example.com/myContentA in my bootstrap tab, instead of #xyz.
Upvotes: 1