Michael
Michael

Reputation: 43

Open jQuery tabs with URL

I have a page with tabs on it that you this jQuery script

http://www.sohtanaka.com/web-design/simple-tabs-w-css-jquery/

I would like to be able to make the tab 3 be the first one open when a user goes to the URL http://mysite.com/about.php#tab3

Is that possible?

Upvotes: 0

Views: 5662

Answers (3)

Viacheslav Molokov
Viacheslav Molokov

Reputation: 2534

According to example you can modifi it in this way:

$(function() {
    $(".tab_content").hide(); //Hide all content
    //On Click Event (left standart)
    $("ul.tabs li").click(function() {

        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content
        var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active ID content
        return false;
    });


    // here we are looking for our tab header
    hash = window.location.hash;
    elements = $('a[href="' + hash + '"]');
    if (elements.length === 0) {
        $("ul.tabs li:first").addClass("active").show(); //Activate first tab
        $(".tab_content:first").show(); //Show first tab content
    } else {
        elements.click();
    }
});

Working example is here. Be careful - hash is hardcoded there, because I don't know how to pass it to test frame :(

Upvotes: 5

Daniel
Daniel

Reputation: 704

I didn't test this, but you should be able to get the hash from the url with:

var hash= window.location.hash;

And then grabbing the link element with the requested hash, and emulating a click on it

$("a[href='"+hash+"']").click();

Upvotes: 2

Todd
Todd

Reputation: 676

Yes, you could make that happen. You will need some code to grab the url and trigger the proper tab though.

Or you could check out Jquery Tools Tabs (http://flowplayer.org/tools/demos/tabs/) or Jquery UI tabs (http://jqueryui.com/demos/tabs/)

Both of these have that functionality (and a ton of other options) already built in.

Upvotes: 0

Related Questions