skip to Main Content

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


  1. Inside the .click function, you can use jQuery(this) to refer to the current element and .find other elements starting from there:

    jQuery(document).ready(function() {
      jQuery(".serviceToggle").click(function(){
        jQuery(this).parent()
        .find(".serviceContent").toggle();
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="serviceCard">
      <div class="serviceContent">
        blah blah blah
      </div>
      <a class="serviceToggle">Learn More</a>
    </div>
    Login or Signup to reply.
  2. The same can of course be done with Vanilla JavaScript and a delegated event listener. This will allow for dynamically added .serviceCard elements:

    document.body.addEventListener("click",ev=>{
      let btn=ev.target;
      if (btn.classList.contains("serviceToggle")){
       let divSt=btn.closest(".serviceCard").querySelector(".serviceContent").style;
       divSt.display=divSt.display==""?"none":"";
      }
    })
    .serviceCard a {color:blue}
    <div class="serviceCard">
      <div class="serviceContent">
        blah blah blah first time
      </div>
      <a class="serviceToggle">Learn More</a>
    </div>
    <div class="serviceCard">
      <div class="serviceContent">
        blah blah blah second time
      </div>
      <a class="serviceToggle">Learn More</a>
    </div>
    <div class="serviceCard">
      <div class="serviceContent">
        blah blah blah third time
      </div>
      <a class="serviceToggle">Learn More</a>
    </div>

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search