Search code examples
htmljqueryshow-hide

Separate show/hide jquery?


I have a problem with a collapsible jquery code.

I'd like to separate some DIVs, but if I click on an element, whichever that is, it opens all of the other elements as well. I have to use more than of these collapsible things (aprox. 40 pieces because there are a lot of versions in one page and I have to save some place). I would like to know how to separate the DIVs from one another. Here is my code:

<script type="text/javascript"
 src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
 $(document).ready(function() {
  $(".flip").click(function() {
   $(".panel").slideToggle("slow");
  });
 });
</script>

<style type="text/css">
div.panel,p.flip {
 margin: 0px;
 padding: 5px;
 text-align: center;
 background: #FFCFF9;
 border: solid 1px #fff;
}

div.panel {
 widht: 50%;
 height: 100px;
 display: none;
}
</style>
</head>
 <div class="panel" id="1">
  <p>Fist panel text</p>
 </div>
 <p class="flip" id="1">1st version</p>
 <div class="panel" id="2">
  <p>Second panel text</p>
 </div>
 <p class="flip" id="2">2nd version</p>

At first I tried this: http://www.dynamicdrive.com/dynamicindex17/animatedcollapse.htm But there was a problem as well; it only shows the content of the first DIV, the rest won't come down. I don't know if I should name the DIVs (as you can see in the code, I've tried that) or not, but if I do, I don't know what's the proper way to do it. Please help me out if you can. Thank you!


Solution

  • Here is a JS fiddle with a working version.

    https://jsfiddle.net/b3bc4yk6/

    The main reason your code was not working is you were not targeting the div you want to expand/contract, you were targeting them all. As you can see from the HTML I have given each panel their own ID.

    <div class="panel" id="panel-1">
      <p>Fist panel text</p>
     </div>
     <p class="flip" id="1">1st version</p>
     <div class="panel" id="panel-2">
      <p>Second panel text</p>
     </div>
     <p class="flip" id="2">2nd version</p>
    

    Also note that an ID should be unique so a flip element and a panel element should not have the same ID.

    Now in the jquery we can grab the ID of the flip and target the specific panel.

    $(document).ready(function() {
      $(".flip").click(function() {
       $("#panel-" + $(this).attr('id')).slideToggle("slow");
      });
     });
    

    Hope that helped!