Default behavior **and** event-binding on a link, is this possible?

is it possible to have default behavior and .onclick event-binking on a link?

I have the code for social-media sharing buttons (for example
<a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo $URL; ?>">FB icon </a> )

but I want to also get an email when a user hits a share button (my site will be low-traffic… so I can do stuff like this…) is it possible to do this? if not, what other way is there to do this? thank you…

it’s possible, although you have a race condition. if the default action eventually kicks in, any running JS is aborted.

You could .preventDefault() as usual, and manually redirect when the response from your mail service is received. Like

document
  .querySelector('.my-link')
  .addEventListener('click', e => {
    const xhr = new XMLHttpRequest()

    xhr.open('POST', 'MyMailService.php')
    xhr.onload = () => {
      window.location.href = e.target.href
    }
    xhr.send()

    e.preventDefault()
  })

This will of course delay the actual redirect a bit, which might not be that great a UX. So if you’re not interested in the response, you might perform the redirect just after the first readystatechange event or something, just to make sure the XHR got really sent.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.