rlm rlm - 9 months ago 20
Javascript Question

specific divs id's showing hidden divs with matching id

I am trying have a "trigger" with a specific

class
show a hidden div that shares the same
class
selected out of a group.

so for example:

when you click

<a class="trigger products">
Products
</a>


it will show the content inside of:

<div class="trigger-children products">
content
</div>


There will be multiple classes's as
.products
is just one. I have the logic down but just not sure how to write it in jquery, and write in the most efficient way. I know it's going to be a
click()
that shows hidden content. So
.trigger-children
will have
display:hidden
in css and be shown on the click.

Please keep in mind that I already have a click event set-up with this system.
.trigger
currently fires it's own
click()
which is doing something different, so not sure if I should combine them. Specifically it is doing:

<script>
$(document).ready(function(){
$(".trigger").click(function () {
$(".hidden-content").slideToggle(200);
});
});
</script>

Answer

This is a perfect requirement for using data-* attributes to specify the elements to target as it keeps the code DRY by requiring only a single click handler. Try this:

$(".trigger").click(function() {
  var targetClass = $(this).data('target');
  $(".trigger-children." + targetClass).slideToggle(200);
});
.trigger-children {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a class="trigger" data-target="products">Products</a>
<a class="trigger" data-target="foo">Foo</a>

<div class="trigger-children products">
  Products content
</div>

<div class="trigger-children foo">
  Foo content
</div>