22_4
22_4

Reputation: 55

JQuery - Show/hide multiple divs with the same class independently


I want to make a collapsible DIV like this:
If you click on the picture (which is in the table and comes with show class) the hidden div slides down (the one with the content class) with it's content and if you click on the hide button or anywhere else on the page, the content div will slide up.
I want to use multiple tables and hidden divs on the page (with the same classes) so i want to make sure to open them independently.

Here is my JSFiddle document, hope that someone can help.
Thanks in advance!

Upvotes: 0

Views: 4161

Answers (1)

Pietro
Pietro

Reputation: 988

You can achieve it with data attributes

<table width="502" style="border:1px solid black; background-color:white;">
  <tr>
    <td align="center" valign="middle" width="300" style="padding:5px">
      Blablabla
    </td>
    <td width="200">
      <a class="show" data-id="1" href="javascript:void(0)"><img src="http://www.placehold.it/200x200"></a>
    </td>
  </tr>
</table>

<div class="content" data-id="1">
  <div class="content-inner">

    <img src="http://www.placehold.it/400x400">
    <p>
      More blablabla
    </p>

    <p class="hide" style="padding-top:50px">Hide</p>
  </div>
</div>

<table width="502" style="border:1px solid black; background-color:white;">
  <tr>
    <td align="center" valign="middle" width="300" style="padding:5px">
      Blablabla
    </td>
    <td width="200">
      <a class="show" data-id="2" href="javascript:void(0)"><img src="http://www.placehold.it/200x200"></a>
    </td>
  </tr>
</table>

<div class="content" data-id="2">
  <div class="content-inner">

    <img src="http://www.placehold.it/400x400">
    <p>
      More blablabla
    </p>

    <p class="hide" style="padding-top:50px">Hide</p>
  </div>
</div>

and change the JS like this

$('.show, .hide').click(function(){
var id = $(this).data('id');

  $('.content[data-id="'+id+'"]').slideToggle('2000', "swing", function() {
  });

});

Upvotes: 4

Related Questions