Home > front end >  How to detect a click on a link or a child of a link?
How to detect a click on a link or a child of a link?

Time:10-12

I'm trying to append some parameters to outgoing clicks using vanilla js so I did this:

document.addEventListener('click', function (e) {
     if (!event.target.matches('a[href*="/outgoing/"]) return;
          e.target.href  = "?this=that" 
}, false);

The problem is that if someone clicks on a div inside of a link for example:

<a href="/outgoing/link.html">
     <div>
       an outgoing link
     </div>
</a>

The target of the link is now the div, not its parent. What is the simplest way to include clicks on children of an <a> tag as well as the tag itself?

CodePudding user response:

Use closest instead of matches. The arguments are the same.

CodePudding user response:

The other answer actually answers your question, but I just wanted to add the fact that your implementation can be a lot more straightforward by applying the event listener just to your elements, therefore the children elements' clicks will bubble up and fire your event listener and you don't have to worry about all that mess. The other advantage is that you won't fire an event listener on every single click on the document, regardless of target.

My implementation would look like this:

document
  .querySelectorAll('a[href*="/outgoing/"]')
  .forEach(i => i.addEventListener('click', function (e) {
    e.target.href  = "?this=that";
  }, false));
  • Related