Question

I am trying to make jquery slidetoggle work for similar divs that look like this

<div id="panel-heading-1"><p>Header</p></div>
  <div id="panel-body-1">
    <p>Text</p>
  </div>
<div id="panel-heading-2"><p>Header</p></div>
  <div id="panel-body-2">
    <p>Text</p>
  </div>
<div id="panel-heading-3"><p>Header</p></div>
  <div id="panel-body-3">
    <p>Text</p>
  </div>

and so on... which are populated dynamically by php

I did try a for loop, and .each() but those does not seem to work, or I am doing them wrong! I am really new to Jquery, so please do explain like I am 5.

Was it helpful?

Solution

Add a common identifier for all your headings (Ex: a class name). And on OnClick event slideToggle the adjacent element. See the example below for reference and this fiddle

To avoid styling effort you can simple use http://jqueryui.com/accordion/

HTML:

    <div class="heading" id="panel-heading-1"><p>Header 1</p></div>
    <div id="panel-body-1">
        <p>Text 1</p>
    </div>
    <div class="heading" id="panel-heading-2"><p>Header 2</p></div>
    <div id="panel-body-2">
        <p>Text 2</p>
    </div>
    <div class="heading" id="panel-heading-3"><p>Header 3</p></div>
    <div id="panel-body-3">
        <p>Text 3</p>
    </div>

Jquery:

    $(".heading").click(function(){
          $(this).next().slideToggle(1300);
    });

OTHER TIPS

okay, i am not that good either, and maybe this isn't what you wanted but it seems to be the easiest solution to me: make several script functions!

first relate to jquery :

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

than use this script:

<script>
$(document).ready(function(){
$("#panel-heading-1").click(function(){
$("#panel-body-1").slideToggle(1300);
});
$("#panel-heading-2").click(function(){
$("#panel-body-2").slideToggle(1300);
});
});
</script>

i only made first two, but repeat this for everything. also set css property display for the panel body's to none. like this:

<style>
#panel-body-1,#panel-body-2,#panel-body-3{
display:none;
}
</style>

that'll make sure they won't be displayed, and toggle to display or none display on every click.

also take notice of the capital T , it doesn't work if it is a small-case t.

(1300) is the time in miliseconds so 1000= 1 second.

i hope this helped you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top