I have a situation where I want to intercept clicks on links that have a most-possibly valid href-attribute and maybe added dynamically after the initial page-load and stop them from following the link. I tried something very similar to this answer on SO:
https://stackoverflow.com/a/33616981/6294605
where my interception-function looks slightly different:
function interceptClickEvent(event) {
let target = event.target || event.srcElement;
let $target = $(target);
console.log(`intercept click event called with closest a: `);
console.log($target.closest(`a`));
if ($target.closest(`a`).length > 0) {
event.preventDefault();
event.stopPropagation();
console.log(`there's a link`);
}
}
But what happens is that this only works on the one link which has this structure:
[...]
<a href=...>
<div>(Site-Logo)</div>
</a>
[...]
But fails at links with this structure:
[...]
<a href=...>
<span>Info</span>
<span>More Info</span>
</a>
[...]
In those second cases it doesn't even arrive at:
console.log(`intercept click event called with closest a: `);
but instead triggers following the link immediately.
Why does that happen?
EDIT: I assume that it is due to another event handler being already attached to the anchor element. See the following fiddle: