medusa1414
medusa1414

Reputation: 1169

jQuery Set active tab from URL

i have this tab-system:

$(document).ready(function(){
    $('#tabs div').hide();
    $('#tabs div:first').show();
    $('#tabs ul li:first').addClass('active');
    $('#tabs ul li a').click(function(){
        if($(this).parent().hasClass('active')) {
            /** active **/
        } else {
            $('#tabs ul li').removeClass('active');
            $(this).parent().addClass('active');
            var currentTab = $(this).attr('href');
            $('#tabs div').hide();
            $(currentTab).show('slide', {}, 500);
        }
        return false;
    });
});

<div id="tabs">
        <ul>
            <li><a href="#tab-1">1</a></li>
            <li><a href="#tab-2">2</a></li>
            <li><a href="#tab-3">3</a></li>
            <li><a href="#tab-4">4</a></li>
            <li><a href="#tab-5">5</a></li>
        </ul>

        <div id="tab-1">
Content tab1
</div>
<div tab2... etc

If i add #tab-3 at the end of the URL, it should automaticly show and set tab 3 active without me have to click it.

Is this possible in a simple way?

Upvotes: 1

Views: 6747

Answers (2)

Matt
Matt

Reputation: 1265

Edited after looking at your code further -

if you code in these two lines every time the DOM is ready you are always going to see that first tab.

$('#tabs div:first').show();
$('#tabs ul li:first').addClass('active');

your going to have to check the url for a '#tab' first before you decide if you should show the first tab.

$(function(){
    ...
    var hash = window.location.hash;
    if(hash){
        $('a[href="' + hash +'"]').parent('li').addClass('active');
        var elementID = hash.replace('#', '');
        $(elementID).show();
    } else {
        $('#tabs div:first').show();
        $('#tabs ul li:first').addClass('active');
    }
    ...
}

Upvotes: 7

orhanhenrik
orhanhenrik

Reputation: 1415

This should probably work:

$(window).bind( 'hashchange', function( event ) {
    var hash=window.location.hash;
    if(!hash){return;}
    $('a[href="'+hash+'"]').click();
});​
$(window).trigger('hashchange');

Upvotes: 2

Related Questions