Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am thinking of to add a javascript function to capture all the <a> click events inside a html page.

So I am adding a global function that governs all the <a> click events, but not adding onclick to each (neither using .onclick= nor attachEvent(onclick...) nor inline onclick=). I will leave each <a> as simple as <a href="someurl"> within the html without touching them.

I tried window.onclick = function (e) {...} but that just captures all the clicks How do I specify only the clicks on <a> and to extract the links inside <a> that is being clicked?

Restriction: I don't want to use any exra libraries like jQuery, just vanilla javascript.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
147 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use event delegation:

document.addEventListener(`click`, e => {
  const origin = e.target.closest("a");
  
  if (origin) {
    console.clear();
    console.log(`You clicked ${origin.href}`);
  }
});
<div>
  <a href="#l1">some link</a>
  <div><a href="#l2"><div><i>some other (nested) link</i></div></a></div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...