jQuery Tabs Back Button Issue
jQuery UI Tabs is a great tool to add tabs on your site. It's easy and works just great. Here I am going to describe the solution for 2 issues
Let's say you have tabs
$('.jquery-tabs').tabs({
activate: function (event, ui) {
const $hash = ui.newPanel.attr('id');
if (history.pushState) {
history.pushState(null, null, window.location.pathname + window.location.search + '#' + $hash);
} else {
window.location.hash = $hash;
}
return false;
},
});
This code above updates the URL every time you change the tab. Event activate( event, ui ) triggered after a tab has been activated (after animation completes). If the tabs were previously collapsed, ui.oldTab and ui.oldPanel will be empty jQuery objects. If the tabs are collapsing, ui.newTab and ui.newPanel will be empty jQuery objects.
The code below reacts on back button click
window.onhashchange = function () {
const $index = $('a[href="' + location.hash + '"]').parent().index();
$('.jquery-tabs').tabs('option', 'active', $index);
}
$index constant will have a li tag number. And on the second line of the function we set the active tab.
Thanks.