Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  14] [ 6]  / answers: 1 / hits: 52616  / 12 Years ago, sun, september 23, 2012, 12:00:00

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.


More From » events

 Answers
7

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>




[edit 2020/08/20] Modernized


[#82952] Thursday, September 20, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacyl

Total Points: 131
Total Questions: 105
Total Answers: 94

Location: Egypt
Member since Tue, May 3, 2022
2 Years ago
stacyl questions
Thu, Jan 28, 21, 00:00, 3 Years ago
Sun, Mar 8, 20, 00:00, 4 Years ago
Tue, Feb 25, 20, 00:00, 4 Years ago
Tue, Feb 11, 20, 00:00, 4 Years ago
;