Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading