12

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 tab by adding the anchor link to it: ex: url.html#tab-4 and pushing the current history of the browser at the same time.

Thank you!

Jerome Ansia
  • 6,854
  • 11
  • 53
  • 99

9 Answers9

36

For jQuery UI 1.10 and later show has been deprecated in favor of activate. Also id is no longer valid jQuery. Use .attr('id') instead. Finally, use on('tabsactivate') instead of bind().

$(function() {
    $("#tabs").tabs({
        activate: function(event, ui) {
            window.location.hash = ui.newPanel.attr('id');
        }
    });
});

Post-creation method:

$("#myTabs").on( "tabsactivate", function(event, ui) {
    window.location.hash = ui.panel.id;
});

Demo: http://jsfiddle.net/RVHzV/

Observable result: http://jsfiddle.net/RVHzV/show/light/

Earlier Version of JQuery

Add a handler to your tab call to update the location hash with the tab id:

$("#myTabs").tabs({
   // options ...
   show: function(event, ui) {
        window.location.hash = ui.panel.id;
   }
});

You can also add this after your UI Tabs are created:

$("#myTabs").bind( "tabsshow", function(event, ui) {
        window.location.hash = ui.panel.id;
});

Code demo: http://jsfiddle.net/jtbowden/ZsUBz/1/

Observable result: http://fiddle.jshell.net/jtbowden/ZsUBz/1/show/light/

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
Jeff B
  • 29,943
  • 7
  • 61
  • 90
  • it's working but the browser scroll down to go to the anchor the other solution is perfect but thanks :) – Jerome Ansia Mar 19 '12 at 20:53
  • You are probably using a newer version of jQuery UI. The `show` method was deprecated for jQuery UI 1.9 and removed for 1.10. It is now called `activate`. Also `id` is no longer supported for jQuery. You need to use `.attr('id')`. Modifications above. – Jeff B Jul 25 '13 at 19:38
  • thanks for the updated code. I am using this tab below a header. Is there anyway to prevent a jump to the href while showing the url? – Neil Feb 04 '14 at 10:25
  • @NeilLittle Hmm. I thought the fix was easy, but it looks like this is a known behavior. Try this question: http://stackoverflow.com/questions/243794 – Jeff B Feb 04 '14 at 19:17
  • @JeffB I think I will register and submit a bug. I thought updating the url location would support SEO Bots crawling the site. – Neil Feb 05 '14 at 12:24
  • @NeilLittle Actually, I rethought this... After some experimentation, I realize the problem is different than the question I linked. The problem, of course, is that you are setting the hash in your address bar, so the browser dutifully updates the address and moves to that location. The trick is to store your current scroll position and restore it after setting the hash. Demo: http://jsfiddle.net/jtbowden/ZsUBz/44/ Fullscreen: http://fiddle.jshell.net/jtbowden/ZsUBz/44/show/light/ – Jeff B Feb 05 '14 at 16:59
  • 1
    The solution to update the hash in the browser window URL bar without scrolling is here: http://stackoverflow.com/questions/8624531/#25577016 Demo here: http://jsfiddle.net/xsx5u5g2/show/#Cats HTH. – JamesWilson Aug 29 '14 at 22:25
10

This should get what you want (using jQuery UI 1.8, in version 1.9 and later use the activate event, see other answers for code example). I used the sample HTML in jQuery UI demos;

        $( "#tabs" ).tabs({
            select: function(event, ui) {                   
                window.location.hash = ui.tab.hash;
            }
        });
Wolfram
  • 8,044
  • 3
  • 45
  • 66
DG3
  • 5,070
  • 17
  • 49
  • 61
  • 3
    @KeyCrumbs.Looks like you are looking at documentation for latest version where the select event is no longer supported. The answer is more than year old.Please look at version 1.8.10 documentation, where the event was supported. Please support your comment by posting your code why it is not working...The OP has marked the answer correct by saying it worked for him...Investigate more before down voting an year old answer.Here is a sample I whipped up for you r benefit http://experiementswithweb.com/testjs/jq.html – DG3 Aug 12 '13 at 00:23
  • 2
    @DG3 Old answers that are no longer valid should be downvoted, its a way of keeping the site up to date. – Toby Allen Jan 05 '14 at 14:30
  • @TobyAllen or better yet, updated with info for newer versions! – redreinard Jul 10 '19 at 21:25
3

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);
    }
  });
});
Dejan Milosevic
  • 1,092
  • 1
  • 11
  • 12
2
$( "#tabs" ).tabs({            
        activate: function(event, ui) {
            //Key => random string
            //url => URL you want to set
            window.history.pushState({key:'url'},'','url');
        }
    });
1

I had to use "create" instead of "activate" to get my initial tab to show in the URL:

    $('#tabs').tabs({
        create: function(event, ui) {
            window.location.hash = ui.panel.attr('id');
        }
    });

This solution seems to be working for changing the URL, but when I go back to the URL it doesn't switch tabs for me. Do I have to do something special to make it switch tabs when that URL is hit?

Billkamm
  • 1,064
  • 1
  • 9
  • 22
  • I remember seeing somewhere that in order to update the page when the hash tag changes by going back in history, you need a javascript that checks the hash value of the url every so many seconds and does whatever it needs to do on the page based on that hash (if you're using the fragment just for a set of tabs, you could simply activate the corresponding tab). – JohnRDOrazio Oct 17 '15 at 08:39
1

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
    }
});
});
leclaeli
  • 139
  • 2
  • 6
0

A combination of the other answers here worked for me.

$( "#tabs" ).tabs({
    create: function(event, ui) {
        window.location.hash = ui.panel.attr('id');
    },
    activate: function(event, ui) {
        window.location.hash = ui.newPanel.attr('id');
    }
});
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
0

I used this method within my jQuery responsive tabs to hash the url with the active tab.

$(function() {
       $('#tabs, #subtabs').responsiveTabs({
            activate: function(event, ui) {
            window.location.hash = $("ul li.r-tabs-state-active a").attr("href");
        },
        startCollapsed: 'accordion'
       });
});
Progrower
  • 363
  • 5
  • 18
0

Although this is old, many of the answers simply don't work. Or work with different HTML structures.

So... an update for 2021 if anyone is interested.

<div class="tabs">
    <ul>
    <li><a href="#personalInformation-content">Personal Information</a></li>
    <li><a href="#profileImage-content">Profile Image</a></li>
    <li><a href="#username-content">Username</a></li>
    <li><a href="#password-content">Password</a></li>
    </ul>


    <div class="tab-content" id="personalInformation-content">
    // Some Tab content 
    </div>

    <div class="tab-content" id="profileImage-content">
    // Some Tab content 
    </div>

    <div class="tab-content" id="username-content">
    // Some Tab content 
    </div>

    <div class="tab-content" id="username-content">
    // Some Tab content 
    </div>
</div>

<script>
$('.tabs').tabs({
    activate: function (event, ui) {  window.location.hash = ui.newPanel.attr('id'); }
});

$( ".tabs" ).on( "tabsactivate", function( event, ui ) {
    window.location.hash = ui.newPanel.attr('id');
    });
</script>
ActiveAdam
  • 25
  • 4