I use a click listener like this so that a click that goes to link.php will execute some code:
document.addEventListener('click', function(e) {
var tre = e.target.href || '';
if( tre.indexOf("link.php") > -1) {
alert('it worked');
}
}, false);
This works:
<a href="/link.php?destination=1" target="_blank">
link text
</a>
But clicks on images or divs don't:
<a href="/link.php?destination=1" target="_blank">
<img src="/image.jpg">
<span>link text</span>
</a>
since clicks are on the image and span, not the <a>
tag. What's the simplest way to make this work?
JavaScript does have a native .closest()
method (although it is currently considered experimental and has limited browser support). You can use this method in order to get the closest a
ancestor element (or the element itself, which means that it would work in both of the cases that you provided).
Example Here
document.addEventListener('click', function(e) {
var href = e.target.closest('a').href || '';
if (href.indexOf("link.php") > -1) {
// ...
}
}, false);
Alternatively, you could check if each parent node is an a
element:
Example Here
document.addEventListener('click', function(e) {
var target = e.target
while (target && target.tagName !== 'A') {
target = target.parentNode;
if (!target) { return; }
}
if (target.href.indexOf("link.php") > -1) {
// ...
}
}, false);
Another option is to attach the event listener directly to the a
element and then access the currentTarget
property in order to get the element that the event was attached to (rather than the element that triggered the event). However, that would only attach the event to a single a
element:
Example Here
document.querySelector('a').addEventListener('click', function(e) {
var href = e.currentTarget.href || '';
if (href.indexOf("link.php") > -1) {
// ...
}
}, false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With