Reputation: 5148
i have a section in my website that needs to be toggled by clicking on the title .
now i wrote this code to toggle when clicking on title
$(document).ready(function(){
$(".toggle_container").hide();
$("h4.trigger").click(function(){
$(this).toggleClass("active").next().slideToggle("slow");
});
});
html part :
<h4 class="trigger"><a href="javascript:void(0)">'.$row[title].'</a></h4>
<div class="toggle_container">
<div class="block">
'.$row[text].'
</div>
</div>
now with these codes everything goes fine , untill it just opens every title clicked and not closes opened ones ;
1st
now i have to change this script in a way that when i click on a title to toggle first check opened ones and close those first
2nd
and the other thing im wondering is how to make the first title to be opened already , when the page loaded the first title to be opened
thanks in advance
Upvotes: 2
Views: 374
Reputation: 630389
I was hoping one of the other answers would update and fix this, but both of them never toggle, they always show, here's how to toggle and hide the others like you want:
$(function(){
$(".toggle_container:gt(0)").hide();
$("h4.trigger").click(function(){
$(this).toggleClass("active").next().slideToggle("slow")
.siblings(".toggle_container").slideUp();
});
});
You can try out a demo here, it shows the first on load, and correctly toggles the rest.
Upvotes: 2
Reputation: 2987
Html
<h4 class="trigger"><a href="javascript:void(0)">Title1</a></h4>
<div class="toggle_container">
<div class="block">
Test
</div>
</div>
<h4 class="trigger"><a href="javascript:void(0)">Title2</a></h4>
<div class="toggle_container">
<div class="block">
Test
</div>
</div>
<h4 class="trigger"><a href="javascript:void(0)">Title2</a></h4>
<div class="toggle_container">
<div class="block">
Test
</div>
</div>
Javascript
$(document).ready(function(){
$(".toggle_container:gt(0)").hide();
$("h4.trigger").click(function(){
$(".toggle_container:visible").slideUp('slow');
$(this).toggleClass("active").next().slideToggle("slow");
});
});
You can check working demo at http://www.jsfiddle.net/XnV69/3/
Upvotes: 1
Reputation: 11824
This should do it I guess
$(document).ready(function(){
$(".toggle_container").hide();
$(".toggle_container:first").show();
$("h4.trigger").click(function(){
$(".toggle_container").hide();
$(this).toggleClass("active").next().slideToggle("slow");
});
});
Upvotes: 1