changing location.hash with jquery ui tabs-Collection of common programming errors

I’ve been trying to find a way to change the window.location.hash to the currently selected tab in Jquery UI Tabs.

I’ve tried:

$("#tabs > ul").tabs();
$("#tabs > ul").bind("tabsshow", function(event, ui) { 
window.location.hash = ui.tab;
})

This results in changing the hash to #undefined when the tab is changed.

I’ve also tried:

$("#tabs > ul").tabs({ 
select: function(event, ui) { 
window.location.hash = ui.tab }
});

But this doesn’t seem to be triggered at all.

Any help would be appreciated. Thanks.

Edit: It looks like part of my initial problem had something to do with js somewhere else interfering with this. Both the accepted answer and the other suggested answer slightly modified do work. Thanks all.

  1. In your event handler function ui.tab is an anchor element. You can retrieve its hash value like this:

    $("#tabs > ul").tabs();
    $("#tabs > ul").bind("tabsshow", function(event, ui) { 
        window.location.hash = ui.tab.hash;
    })
    

    Does this work for you?

  2. $('#tabs').tabs({
        select: function(event, ui) {
            window.location.hash = ui.tab.hash;
        }
    });
    
  3. While some of the above solutions work, they cause the page to jump around in some cases, as the window.location.hash API is designed to bring you to a specific part of the page.

    This neat solution proposed here, solves that issue

      $("#tabs").bind("tabsshow", function(event, ui) { 
        history.pushState(null, null, ui.tab.hash);
      });
    
  4. Would this be what you’re going for?

    $("#tabs > ul").tabs({ 
       select: function(event, ui) 
       { 
          window.location = "#" + ui.tab;
       }
    });
    
  5. $('#tabs').tabs({
        select: function(event, ui){
          window.location = ui.tab.href;
        }
    });
    
  6. It seems like ui.tab itself doesn’t return a valid string. (instead it returns undefined, so you’d say it doesn’t return anything at all.)

    Try looking around in the dev version of ui.jquery.js whether there are any returns there, maybe you have to call a child of ui.tab 😉

  7. Many of the above answers don’t work with the current version of jQuery UI Tabs. Here’s what I’m currently using:

    var tabsUi = $('#tabs');
    tabsUi.tabs();
    
    // Add hash to URL when tabs are clicked
    tabsUi.find('> ul a').click(function() {
        history.pushState(null, null, $(this).attr('href'));
    });
    
    // Switch to correct tab when URL changes (back/forward browser buttons)
    $(window).bind('hashchange', function() {
        if (location.hash !== '') {
            var tabNum = $('a[href=' + location.hash + ']').parent().index();
            tabsUi.tabs('option', 'active', tabNum);
        } else {
            tabsUi.tabs('option', 'active', 0);
        }
    });
    

Originally posted 2013-11-09 19:46:10.