jQuery UI tabs, update url when clicking on a different tab
Asked Answered
M

9

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!

Menstruum answered 19/3, 2012 at 20:33 Comment(3)
can you give some more info please? It is not clear what you are asking...Submarine
ok i'll try seems clear to me :pMenstruum
ok done, let me know if it's fine like this ;)Menstruum
U
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;
            }
        });
Uriiah answered 19/3, 2012 at 20:44 Comment(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 experiementswithweb.com/testjs/jq.htmlUriiah
@Uriiah Old answers that are no longer valid should be downvoted, its a way of keeping the site up to date.Ribeiro
@TobyAllen or better yet, updated with info for newer versions!Possum
I
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/

Inclinometer answered 19/3, 2012 at 20:43 Comment(7)
it's working but the browser scroll down to go to the anchor the other solution is perfect but thanks :)Menstruum
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.Inclinometer
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?Umbilicate
@NeilLittle Hmm. I thought the fix was easy, but it looks like this is a known behavior. Try this question: stackoverflow.com/questions/243794Inclinometer
@JeffB I think I will register and submit a bug. I thought updating the url location would support SEO Bots crawling the site.Umbilicate
@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: jsfiddle.net/jtbowden/ZsUBz/44 Fullscreen: fiddle.jshell.net/jtbowden/ZsUBz/44/show/lightInclinometer
The solution to update the hash in the browser window URL bar without scrolling is here: stackoverflow.com/questions/8624531/#25577016 Demo here: jsfiddle.net/xsx5u5g2/show/#Cats HTH.Fend
U
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;
            }
        });
Uriiah answered 19/3, 2012 at 20:44 Comment(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 experiementswithweb.com/testjs/jq.htmlUriiah
@Uriiah Old answers that are no longer valid should be downvoted, its a way of keeping the site up to date.Ribeiro
@TobyAllen or better yet, updated with info for newer versions!Possum
B
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);
    }
  });
});
Batten answered 2/4, 2015 at 10:17 Comment(1)
This one works well with code.jquery.com/ui/1.12.1/jquery-ui.jsPhane
S
2
$( "#tabs" ).tabs({            
        activate: function(event, ui) {
            //Key => random string
            //url => URL you want to set
            window.history.pushState({key:'url'},'','url');
        }
    });
Storebought answered 26/5, 2015 at 11:31 Comment(0)
U
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?

Ule answered 16/8, 2013 at 14:28 Comment(1)
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).Negligee
R
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
    }
});
});
Reserve answered 23/1, 2015 at 20:27 Comment(1)
nice solution taking care of scroll positionNegligee
G
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');
    }
});
Goner answered 6/2, 2015 at 14:32 Comment(0)
S
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'
       });
});
Sprinkler answered 22/6, 2016 at 12:25 Comment(0)
P
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>
Psychedelic answered 20/8, 2021 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.