Capturing all the <a> click event
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
window.onclick = function (e) {
if (e.target.localName == 'a') {
console.log('a tag clicked!');
}
}
The working demo.
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>
your idea to delegate the event to the window and then check if the "event.target" is a link, is one way to go (better would be document.body). The trouble here is that it won't work if you click on a child node of your element. Think:
<a href="#"><b>I am bold</b></a>
the target
would be the <b>
element, not the link. This means checking for e.target
won't work. So, you would have to crawl up all the dom tree to check if the clicked element is a descendant of a <a>
element.
Another method that requires less computation on every click, but costs more to initialize would be to get all <a>
tags and attach your event in a loop:
var links = Array.prototype.slice.call(
document.getElementsByTagName('a')
);
var count = links.length;
for(var i = 0; i < count; i++) {
links[i].addEventListener('click', function(e) {
//your code here
});
}
(PS: why do I convert the HTMLCollection to array? here's the answer.)