jQuery UI tabs, update url when clicking on a different tab

前端 未结 8 773
甜味超标
甜味超标 2020-12-09 11:56

I\'m using the tabs of jQuery UI: http://jqueryui.com/demos/tabs/

How to update the current url of the browser when the user click on a different ta

相关标签:
8条回答
  • 2020-12-09 12:37

    Building off of Jeff B's work above...this works with jQuery 1.11.1.

    $("#tabs").tabs(); //initialize tabs
    $(function() {
        $("#tabs").tabs({
            activate: function(event, ui) {
                var scrollTop = $(window).scrollTop(); // save current scroll position
                window.location.hash = ui.newPanel.attr('id'); // add hash to url
                $(window).scrollTop(scrollTop); // keep scroll at current position
        }
    });
    });
    
    0 讨论(0)
  • 2020-12-09 12:39

    First, we need to update the hash on tab change (this is for latest jQueryUI):

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

    Then we need 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);
        return;
      }
      $('#tabs > ul > li > a').each(function (index, a) {
        if ($(a).attr('href') == location.hash) {
          $('#tabs').tabs('option', 'active', index);
        }
      });
    });
    
    0 讨论(0)
提交回复
热议问题