How to properly update URL hash upon selecting a jQuery tab?
Asked Answered
I

2

7

HTML:

<div id="tabs">
    <ul>
        <li><a href="#settings">Settings</a></li>
        <li><a href="#fields">Fields</a></li>
    </ul>
    <div id="settings">
        //Tab Contents
    </div>
    <div id="fields">
        //Tab Contents
    </div>
</div>

How can I apply jQueryUI's Tab functionality and force it to update the URL hash upon selecting a new tab?

Indulge answered 25/7, 2013 at 18:41 Comment(0)
D
7

Besides updating the hash on tab change (with the beforeActivate event as in shruggernaut's reply) it is very useful to update the active tab on hash change (i.e. enabling browser history, back/forward buttons and user typing in the hash manually):

$(window).on('hashchange', function () {
  if (!location.hash) {
    $('#tabs').tabs('option', 'active', 0); // activate first tab by default
    return;
  }
  $('#tabs > ul > li > a').each(function (index, a) {
    if ($(a).attr('href') == location.hash) {
      $('#tabs').tabs('option', 'active', index);
    }
  });
});
Doodlebug answered 2/4, 2015 at 10:13 Comment(0)
I
21

Use this code to create your jQuery UI tabs:

$('#tabs').tabs({
    beforeActivate: function (event, ui) {
        window.location.hash = ui.newPanel.selector;
    }
});

I created this answer because I cannot find a single one with an up-to-date method. Hope this helps somebody else!

Indulge answered 25/7, 2013 at 18:41 Comment(2)
FYI - In older version of jQuery, it is 'select' instead of 'beforeActivate'Bessette
FYI-2 - In older version of jQuery, it is 'ui.panel.id' instead of 'ui.newPanel.selector' (at least that worked for me)Homebrew
D
7

Besides updating the hash on tab change (with the beforeActivate event as in shruggernaut's reply) it is very useful to update the active tab on hash change (i.e. enabling browser history, back/forward buttons and user typing in the hash manually):

$(window).on('hashchange', function () {
  if (!location.hash) {
    $('#tabs').tabs('option', 'active', 0); // activate first tab by default
    return;
  }
  $('#tabs > ul > li > a').each(function (index, a) {
    if ($(a).attr('href') == location.hash) {
      $('#tabs').tabs('option', 'active', index);
    }
  });
});
Doodlebug answered 2/4, 2015 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.