Search code examples
jqueryjquery-uitabsfragment-identifier

changing location.hash with jquery ui tabs


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.


Solution

  • 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?