Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing all the <a> click event

Tags:

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.

like image 837
user1589188 Avatar asked Sep 23 '12 11:09

user1589188


People also ask

Which method will help you capture all the click events in a window?

captureEvents() method registers the window to capture all events of the specified type.

How do you capture an event?

Event capturing is one of two ways to do event propagation in the HTML DOM. In event capturing, an event propagates from the outermost element to the target element. It is the opposite of event bubbling, where events propagate outwards from the target to the outer elements.


2 Answers

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

like image 98
KooiInc Avatar answered Oct 14 '22 15:10

KooiInc


You can handle all click using window.onclick and then filter using event.target

Example as you asked:

<html> <head> <script type="text/javascript"> window.onclick = function(e) { alert(e.target);}; </script> </head> <body> <a href="http://google.com">google</a> <a href="http://yahoo.com">yahoo</a> <a href="http://facebook.com">facebook</a> </body> </html> 
like image 23
Artur Udod Avatar answered Oct 14 '22 14:10

Artur Udod