Jquery Tabs - Activate on Button Click
by Jaganathan
HTML
<ul class="tabs">
<li><a href="#tab1">Tab 1</a></li>
<li><a href="#tab2">Tab 2</a></li>
</ul>
<div class="tab-content">
<div id="tab1">
<p>Content 1</p>
<button>activate 2nd tab</button>
</div>
<div id="tab2">
<p>Content 2</p>
</div>
</div>
CSS
* {
padding: 0;
margin: 0;
}
body {
margin: 30px;
}
.tabs {
overflow: hidden;
list-style: none;
}
.tabs li {
float: left;
margin-right: 10px;
border: 1px solid #ccc;
border-bottom: 0;
}
.tabs a {
display: block;
padding: 5px;
width: 100px;
}
.tabs a.active {
background: #efefef;
}
.tab-content > div {
padding: 10px;
border: 1px solid #ccc;
}
button {
padding: 5px;
}
JavaScript
$(function() {
var activate = false,
tabLinks = $('.tabs a');
tabContent = $('.tab-content').children();
tabLinks.eq(0).addClass('active'); // Add active class, could possibly go in markup
$('#tab2').hide(); // Hide second tab
tabLinks.bind('click', function(e) {
e.preventDefault();
if(activate === true) { // Only do something if button has been clicked
var target = this.hash,
el = $(this);
tabLinks.filter('.active').removeClass('active');
el.addClass('active');
tabContent.hide(); // Hide all
$(target).show(); // Show selected
}
});
$('button').bind('click', function() {
activate = true; // Activate tab functionality
tabLinks.eq(1).trigger('click'); // Trigger a click on the second tab link
});
});