I have about 9 cards on my site. Here is the structure of one card:
<div class="serviceCard">
<div class="serviceContent">
blah blah blah
</div>
<a class="serviceToggle">Learn More</a>
</div>
I am using the below jQuery to toggle the content of the card, but it’s affecting all my cards since they all use the same class. How can I adjust my code so that it only affects the card that I am clicking on?
jQuery(document).ready(function() {
jQuery(".serviceToggle").click(function(){
jQuery(".serviceContent").toggle();
});
});
2
Answers
Inside the
.click
function, you can usejQuery(this)
to refer to the current element and.find
other elements starting from there:The same can of course be done with Vanilla JavaScript and a delegated event listener. This will allow for dynamically added
.serviceCard
elements:I used
.closest()
instead of `.parent() (a function of the same name and functionality is also available in jQuery!) as it makes the script more tolerant towards possible layout changes in the HTML.