changing location.hash with jquery ui tabs

Rob picture Rob · Feb 20, 2009 · Viewed 65.4k times · Source

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.

Answer

Serxipc picture Serxipc · Feb 20, 2009

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?