Remember last active Vertical Tab using Cookies in Drupal

This is a quick reminder to myself so I don't forget in future. I need a way of remember what vertical tab was last active when the user revisits or refreshes the page. The only good way of doing this is by using cookies. The first thing to do is add the jquery.cookie.js file that ships with Drupal so we can use cookies within our JS:

('system', 'jquery.cookie');

or if the vertical tabs are in a form it would be better to add this via hook_form_alter() instead:

 * Implements hook_form_alter().
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
$form['#attached']['library'][] = array('system', 'jquery.cookie');

Now create a JS file and name it anything you like, for example custom-vertical-tabs.js, and use drupal_add_js() or attach it to your form. Inside custom-vertical-tabs.js add the following code and clear the Drupal cache for luck. It should now remember the last active tab.

(function ($) {
Drupal.behaviors.verticalTabRemember = {
  attach: function (context, settings) {
    if (document == context) {
      var container = $('#block-system-main');
      $('.vertical-tabs-list li a', container).click(function() {
        var index = $(this).parent().index();
        // Use a cookie to remember tab index for this page only
        $.cookie('dashboard_tab', index, { path: window.location.pathname });
      // If there is a cookie remembering last tab, activate that tab.
      if ($.cookie('dashboard_tab') !== null) {
        $('.vertical-tabs-panes .vertical-tabs-pane', container).eq($.cookie('dashboard_tab')).data('verticalTab').focus();

What this is doing is creating a cookie that remembers the index of the active tab when clicked, for this page only. When the page loads again, it checks first to see if the cookie exists and if it does it loads the panel by index, otherwise the first tab is activated.