jQuery Tabs Back Button Issue
the image is taken from nicesnippets.com

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

  1. URL needs to be updated so you can directly navigate to the tab from URL.
  2. When you click back button, and the URL updates, select the tab by URL hash. (by default, nothing happens).

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.

Buy me a coffee

To view or add a comment, sign in

More articles by Gene C.

Explore content categories