I have a series of bootstrap 4.6 tabs on a page and I want any of these tabs to be opened via the hash value in a url. Using this thread as a start off-point, I have been able to detect a hash value at the end of the page url in a document.ready function like so, but for some reason the targeted tab is never clicked:
$(document).ready(function($) {
function onHashChange() {
var hash = window.location.hash;
if (hash) {
// using ES6 template string syntax
$(`[data-toggle="tab"][href="${hash}"]`).trigger('click');
// None of these seem to work either
$(hash).trigger('click');
$(hash)[0].click();
$(hash).click();
}
}
window.addEventListener('hashchange', onHashChange, false);
onHashChange();
})
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
I have confirmed that the $(hash) selector is finding the correct element, but it is never changed by the script. How can I modify my code so the targeted tab element is clicked and the correct tab content is shown when my page loads?