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

144
Views
How to execute function when anchor tag was opened?

I want to send a post request (with a payload) to my server when a user opens a link in my React app.

My current approach is to use the onClick and onAuxClick callbacks, and then filter out right-clicks (because those don't directly open links).

<a href={link} target="_blank" rel="noopener noreferrer" 
onClick={onLinkClicked} onAuxClick={onLinkClicked}>
    <FaExternalLinkAlt className={styles.headerButton} />
</a>
function onLinkClicked(event: MouseEvent) {
    if ([0,1].includes(event.button)) {
        alert('track click')
    }
}

However, right clicks followed by opening the link via the context menu are also ignored.

Another option seems to be to use the ping callback. However, there are two problems with this: Ping doesn't seem to contain a payload/body, which I need. And browser support seems to be flaky.

How can I reliably track link clicks without false positives and without ignoring opening the link via the context menu (and any other ways of opening a link)?

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

0

You can force the link to be opened even if the user clicks the wrong button and with that you ensure the actual click count

Edit 1:

For some reason, the contextmenu event fires twice so I advise that you handle that issue I tried removing the event propagation and investigating on it and found nothing

const a  = document.querySelector('a');

//              left,     right,         middle      Clicks
const events = ['click', 'contextmenu', 'auxclick'] // You can add more events if you feel the need to

const cb = (clickType, elem) => {
  console.log(clickType);
  console.log(elem.href);
  
  // Open link and do the post request here
}


events.forEach(eve => {
  a.addEventListener(eve, (e) => {
      e.preventDefault();
      cb(e.which, a);

  })

})
<a href="https://stackoverflow.com/">click</a>

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!