Reputation: 27
I am trying have a "trigger" with a specific class
show a hidden div that shares the same class
selected out of a group. For example when you click this:
<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 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:
$(document).ready(function(){
$(".trigger").click(function () {
$(".hidden-content").slideToggle(200);
});
});
https://jsfiddle.net/RalphLeMouf/ng86b7z3/
Upvotes: 1
Views: 52
Reputation: 337580
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>
Upvotes: 1