mkas
mkas

Reputation: 513

Link to particular tab in JavaScript

I have a sample page with three tabs (tabs.html). Tabs are displayed as follows:

<ul class="tabs">
    <li><a href="javascript:tabSwitch('tab_1', 'content_1');" id="tab_1" class="active">Tab 1</a></li>
    <li><a href="javascript:tabSwitch('tab_2', 'content_2');" id="tab_2">Tab 2</a></li>
    <li><a href="javascript:tabSwitch('tab_3', 'content_3');" id="tab_3">Tab 3</a></li>
</ul>

The JavaScript used to switch tabs is:

function tabSwitch(active, number, tab_prefix, content_prefix) {
    for (var i = 1; i < number+1; i++) {  
        document.getElementById(content_prefix+i).style.display = 'none';  
        document.getElementById(tab_prefix+i).className = '';  
    }  
    document.getElementById(content_prefix+active).style.display = 'block';  
    document.getElementById(tab_prefix+active).className = 'selected';      
}

Now, by default, when I link to tabs.html, the first tab is set to active. Is it possible to create a link from another site that links to tabs.html and forces the second or third tab to be active?

Upvotes: 0

Views: 228

Answers (3)

mtrovo
mtrovo

Reputation: 879

You can try to get the tab you want to add from the hash like tabs.html#tab1. Then on a code block that run on the page onload do something like this:

var hash = window.location.hash;
if (hash == "#tab1")
    tabSwitch('tab_1', 'content_1');
else if (hash == "#tab2")
    tabSwitch('tab_2', 'content_2');
else if (hash == "#tab3")
    tabSwitch('tab_3', 'content_3');

I don't know if you're doing it by itself to learn javascript, but there is a jquery plugin named jQuery Tabs that does exactly what you're trying to do.

Upvotes: 0

borrel
borrel

Reputation: 922

yes just append your options to the url like tabs.html?1 and then check window.location.search.substr(1) for your tabnumber onload

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78520

document.body.onload = function(){
    if (location.hash !== "")
    {
        var page = location.hash.match(/[0-9]/);
        tabSwitch('tab_'+page, 'content_'+page);
    }
}

That should work for setting the correct tab. Then a link would be something like http://www.example.com/tabs.html#tab_1

Upvotes: 1

Related Questions