views:

11270

answers:

7

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

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.

[1]: http://docs.jquery.com/UI/Tabs"Jquery UI Tabs"

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.

+2  A: 

Would this be what you're going for?

$("#tabs > ul").tabs({ 
   select: function(event, ui) 
   { 
      window.location = "#" + ui.tab;
   }
});
hunter
I tried this without any luck. I even tried putting an alert prior to the window.location setting and it doesn't appear when changing tabs. The only way I could get it to activate was by binding tabsshow but that ends up with an undefined ui.tab
Rob
When I tried using the demo code this solution slightly modified did work. The only change I would suggest is making it:window.location.hash = ui.tab.hash;
Rob
+7  A: 

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?

Serhii
Unfortunately no, I receive many ui.tab is undefined errors upon page load or tab change.
Rob
I've been trying with the demo that appears on the doc page and works fine with FF 3 and IE 7. Are you triggering the events manually?
Serhii
I tried as you suggested with the demo page and your solution did end up working, thanks for the solution, I'll have to figure out what else in my code was stopping it from working. Thanks
Rob
If you are testing on Firefox, install the Firebug extension and put a console.trace() to track where the problems come from.
Serhii
+2  A: 

$('#tabs').tabs({ select: function(event, ui){ window.location = ui.tab.href; } });

A: 

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 ;-)

A: 

this is a pretty awesome demo of this technique: http://jqueryfordesigners.com/jquery-tabs/

Will
A: 

I'm using this plugin: http://flowplayer.org/tools/demos/tabs/ajax-history.htm

FDisk
A: 
$('#tabs').tabs({
    select: function(event, ui) {
        window.location.hash = ui.tab.hash;
    }
});
Herman van der Meulen