Search code examples
javascriptjqueryevent-handlingdom-eventsevent-delegation

Remove click event on specific element where the event is called in multiple places


I have multiple card generated from a loop which share the same functionality. One of them is to Like and Dislike buttons. It's someone's code, I was asked to remove the click event per card once the user click on Like/Dislike button. I don't know how to remove/disable the click event when one choice is picked as it might disable other cards buttons.

I updated the original code for more clarity

function contentLike_Dislike(contentid, islike) {
  if (islike === "true") {
    var likeP = $("#p-like-" + contentid).text();
    $("#p-like-" + contentid).text(parseInt(likeP) + 1);

    $(".fa-thumbs-up").click(function () {
      $(this).removeClass("far").addClass("fa"); 
    });
  } else {
    var dislikeP = $("#p-dislike-" + contentid).text();
    $("#p-dislike-" + contentid).text(parseInt(dislikeP) + 1);

    $(".fa-thumbs-down").click(function () {
      $(this).removeClass("far").addClass("fa"); 
    });
  }
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>

<div class="col-lg-6 d-flex justify-content-lg-end">
  <a href="javascript:void(0)"
     onclick="contentLike_Dislike('21785', 'true')"
     class="text-navy-custom font-r fs-small me-3 d-flex"
  >
    <i class="far align-self-center fa-thumbs-up me-2 align-self-center"
       aria-hidden="true">
    </i>
    <p id="p-like-21785"
       class="mb-0 align-self-center d-none"
       tabindex="0">
      0
    </p>
  </a>
  <a href="javascript:void(0)"
     onclick="contentLike_Dislike('21786', 'false')"
     class="text-navy-custom font-r fs-small me-3 d-flex"
  >
    <i class="far align-self-center fa-thumbs-down me-2 align-self-center"
       aria-hidden="true">
    </i>
    <p id="p-dislike-21786"
       class="mb-0 align-self-center d-none"
       tabindex="0"
    >
      0
    </p>
  </a>
</div>


Solution

  • By using the parent element to select buttons, you can disable only those that are within the same parent. This is optimal for the situation where you have multiple cards on the same page.

    function contentLike_Dislike(event, islike) {
        if (islike === 'true') {
          alert("like");
        } else {
          alert("dislike");
        }
        
        var buttons = event.target.parentNode.querySelectorAll("button");
        buttons.forEach((item) => {
            item.onclick = "";
        });
    }
    <div class="card">
      <button onclick="contentLike_Dislike(event, 'true')">Like</button>
      <button onclick="contentLike_Dislike(event, 'false')">Dislike</button>
    </div>