user17144244
user17144244

Reputation:

How to consolidate 2 functions into a single one (Use one function to target multiple classes)

I have 2 functions doing the same thing, just targeting two different classes on my page. Is there a way to consolidate these two into a single function?

$(document).on("click", ".class1", function(event) {
      const $this = $(this);
      if ($this.find($(event.target).closest("a")[0]).length === 0) {
          event.preventDefault();
          $this.find("a")[0].click();
      }
  });

  $(document).on("click", ".class2", function(event) {
      const $this = $(this);
      if ($this.find($(event.target).closest("a")[0]).length === 0) {
          event.preventDefault();
          $this.find("a")[0].click();
      }
  });

I have a lot of cards on the page that have the class1 and class2 name, I know I can give them each an extra class something like .clickable and add it to every single card on the page, but I was wondering if there's an easier way to just have this function target 2 classes at once.

Upvotes: 0

Views: 89

Answers (1)

Kinglish
Kinglish

Reputation: 23654

You can put them together like this

to activate the anchor link on the first matching <a> element

$(document).on("click", ".class1, .class2", function(event) {
  if ($(this).find($(event.target).closest("a")[0]).length === 0) {
          event.preventDefault();
          $(this).find("a")[0].click();
      }
     // $(event.target).find("a").eq(0)[0]?.click();
});
.padd {
  padding: 30px;
  background: #f0f0f0;
  margin-bottom: 20px;
}

#gohere{
margin-top:500px;
height:300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='class1 padd'>
  <a href='#gohere' onclick='console.log("CLICKED1")'>the link</a><br>
  <a href='#' onclick='console.log("this should not fire....")'>a second link</a>
</div>

<div class='class2 padd'>
  <a href='#' onclick='console.log("CLICKED2")'>the link</a>
</div>


<div class='class2 padd'>
  no link here
</div>


<div id='gohere'>Anchor link text....</div>

Upvotes: 1

Related Questions