Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!