GCW
GCW

Reputation: 312

Single function to toggle multiple divs inside other divs individually

I have some divs in my page, and each one of them has got a content I want to toggle via jQuery. This is actually how my code looks like:

$('.my_div').click(function() {
   $( ".my_div_B" ).slideToggle( "slow" );
 });

$('.my_div2').click(function() {
   $( ".my_div_B2" ).slideToggle( "slow" );
 });

$('.my_div3').click(function() {
   $( ".my_div_B3" ).slideToggle( "slow" );
 });

and so on... of course it's not the best way to do that, repeating the name of the divs always in the same part of code.

HTML pattern:

<div class="my_div">
<img />
<img />
<div class="my_div_B">text</div>
</div>

How can I make it shorter without opening ALL my divs clicking on $('this')? - ps. I know there are some similar questions, but the answers seem to be specific for that markup.

Upvotes: 2

Views: 497

Answers (1)

Alex Char
Alex Char

Reputation: 33218

You can check if div has specific class value like:

//select div with class attribute starts with my_div
$('div[class^="my_div"]').click(function() {
  //find child element div with class start my_div_B
  $(this).children("div[class^='my_div_B']").slideToggle("slow");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my_div">
  <img src='http://placehold.it/200x100' />
  <img src='http://placehold.it/200x100' />
  <div class="my_div_B">text</div>
</div>
<div class="my_div2">
  <img src='http://placehold.it/200x100' />
  <img src='http://placehold.it/200x100' />
  <div class="my_div_B2">text</div>
</div>

Upvotes: 5

Related Questions