Reputation: 315
Made a simple jquery tab widget. It runs fine as is but I want to run it with no tabs or panels open when it first loads. In order to do this I remove the class active tags from the first tab and first panel (id panel1) but then it doesn't run. No idea why.
HTML :
<div class="wrapper tab-panels">
<ul class="tabs">
<li rel="panel1" class="active">panel1</li>
<li rel="panel2">panel2</li>
<li rel="panel3">panel3</li>
<li rel="panel4">panel4</li>
</ul>
<div class="panel active" id="panel1">
conten1<br>
conten1<br>
conten1<br>
conten1<br>
conten1<br>
</div>
<div class="panel" id="panel2">
conten2<br>
conten2<br>
conten2<br>
conten2<br>
conten2<br>
</div>
<div class="panel" id="panel3">
conten3<br>
conten3<br>
conten3<br>
conten3<br>
conten3<br>
</div>
<div class="panel" id="panel4">
conten4<br>
conten4<br>
conten4<br>
conten4<br>
conten4<br>
</div>
</div>
JQUERY :
$(function () {
$(".tab-panels .tabs li").on("click", function () {
var $panel = $(this).closest(".tab-panels");
if ($(this).hasClass("active") == true) {
$(this).removeClass("active");
$(".tab-panels .panel.active").slideUp(300);
} else {
$panel.find(".tabs li.active").removeClass("active");
$(this).addClass("active");
var panelToShow = $(this).attr("rel");
function showNextPanel() {
$(this).removeClass("active");
$("#" + panelToShow).slideDown(300, function () {
$(this).addClass("active");
});
}
$panel.find(".panel.active").slideUp(300, showNextPanel);
}
});
});
CSS:
.tab-panels ul {
margin: 0;
padding: 0;
}
.tab-panels ul li {
list-style-type: none;
display: inline-block;
background: red;
margin: 0;
padding: 3px 10px;
color: white;
cursor: pointer;
}
.tab-panels ul li:hover {
color: #fff;
background: #666;
}
.tab-panels ul li.active {
color: #fff;
background: #666;
}
.tab-panels .panel {
display: none;
background: blue;
padding: 10px;
}
.tab-panels .panel.active {
display: block;
}
Upvotes: 0
Views: 119
Reputation: 9583
your code works fine you just need to set an initial condition in the css:
.panel:not(.active){
display:none
}
Upvotes: 0
Reputation: 7288
Check out this JSFiddle, it starts with sliding up all panel and remove all active class from all elements.. Then when you clicked a panel, it will close another panel then open up the selected panel..
$(document).ready(function(){
$(".tab-panels .tabs li").each(function(){
$(this).removeClass("active");
});
$(".tab-panels .panel").each(function(){
$(this).slideUp(300);
});
$(".tab-panels .tabs li").on("click", function () {
if($(this).hasClass("active") == true){
$(this).removeClass("active");
var selected_panel = $(this).text();
$(".tab-panels #"+selected_panel).slideUp(300);
}
else{
$(".tab-panels .tabs li.active").removeClass("active");
$(".tab-panels .panel").each(function(){
$(this).removeClass("active");
$(this).slideUp(300);
});
$(this).addClass("active");
var selected_panel = $(this).text();
$(".tab-panels #"+selected_panel).slideDown(300);
}
});
});
Upvotes: 0