Reputation: 737
I have the following code: fiddle, how can I set it up so I can have urls to the different tabs, I have tried adding the tab id to the url and that doesn't work. I have also tried anchors and that doesn't work, any help appreciated.
Upvotes: 0
Views: 648
Reputation: 23580
You can do this very easy. As your list is corresponding to the tabs semself in the order of appearance you don't need the ids and you can do it like this:
<ul id="tabs">
<li><a href="http://domain.com/#tab1">test1</a></li>
</ul>
<div>
<div class="container">Some content1</div>
</div>
var tabs = $('#tabs a');
var content = $('.container');
var current = 0;
tabs.click( function(event) {
// get which element was clicked
var pos = tabs.index ($(event.target) );
// remove current active class
tabs.eq(current).removeClass('active');
// fade out current element
content.eq(current).fadeOut( function() {
//afterwards set current to selected, update class and fade in content
current = pos;
tabs.eq(current).addClass('active');
content.eq( current ).fadeIn();
// append hash to url
window.location.hash = tabs.eq(current).attr('href');
});
event.preventDefault();
});
This is the line that adds the anchor to the URL:
window.location.hash = tabs.eq(current).attr('href');
Note, that this won't work in the fiddle. Or you can leave this line out and add real urls like I did in the source code above.
I also optimized your code, in order that uses less selectors and it's a little shorter. And it also uses a single class active
for the current element (instead of applying a class to all inactive
elements). You just have to adjust your styles.
I also added some CSS which shows the first element by default and hides all other - no JavaScript needed:
.container {
display:none;
}
.container:first-child {
display:block;
}
http://jsfiddle.net/insertusernamehere/hCWMj/
Upvotes: 1
Reputation: 4092
You'll have to trigger the tab switch function manually by binding a click event.
HTML:
<ul id="tabs">
<li><a href="#tab1">test1</a></li>
<li><a href="#tab2">test2</a></li>
<li><a href="#tab3">test3</a></li>
<li><a href="#tab4">test4</a></li>
</ul>
<span class="tablink" data-href="#tab1">link</span>
JS:
$('.tablink').click(function(){
$('a[href="'+$(this).attr('data-href')+'"]').click();
});
this link will work as if you've clicked the tab.
It will find the link that activates your tab, and fire it's click event.
Edited to fit asker's HTML
Upvotes: 1