tags:

views:

37

answers:

3

hey

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

+1  A: 

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");
  });
});
Ergec
This would always show the next `.toggle_container` on click, since you're hiding *all* of them on each click, making the toggle state/`.active` class an invalid representation of what's going on.
Nick Craver
+1  A: 

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/

Kai
This suffers from the same problem as the other answer...it'll always show, never toggle :) Should be something like this: http://www.jsfiddle.net/XnV69/4/
Nick Craver
+2  A: 

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.

Nick Craver
thank you so much , wow . that was so smart
Mac Taylor