How to open specific Bootstrap tab by clicking on a link
Solution 1:
You don't really need to check the fragment to switch between those tabs.
1) Import jQuery from here or:
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
2) Add this part to your code.
<script>
$(document).ready(function () {
$('.nav-tabs a').click(function () {
$(this).tab('show');
});
});
</script>
Solution 2:
I already started answering your old question before you deleted it, but here is it again. I didn't understood what you were trying to achieve, so I just looked into the code and made my version, its not the best but it works.
This is an onClick event handler, it gets executed on a click in your nav and changes the active classes.
// onClick event handler, gets executed on click
$(".nav-link").on("click", (e) => {
// store clicked element
const listItem = e.target;
// get hash
const hash = e.target.hash;
// remove all active classes
$(".nav-link, .tab-pane").removeClass("active");
// add active class to list item and tab panes
$(listItem).add(hash).addClass("active");
});
This part gets executed when you reload your page. You need to change your HTML for this to work, so remove the active class from nav-link and give every link an additional class (tabs-1, tabs-2 and tabs-3).
// when page is reloaded
$(document).ready(() => {
// get current hash
const hashList = window.location.hash;
const hashItems = hashList.slice(1);
// remove all active classes
$(".nav-link, .tab-pane").removeClass("active");
// add active class to nav-link and pane
$(hashList).add(`.${hashItems}`).addClass("active");
});
Both snippets need to be included in your script tag of course, also you need to import jQuery, if not already happened.