0

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:

http://jsfiddle.net/vkoj74da/8/

Wolfone
  • 1,276
  • 3
  • 11
  • 31
  • Could you provide a runnable snippet that demonstrates that the click is not intercepted? – trincot Jan 05 '19 at 10:53
  • 1
    It seems to be working in the fiddle here: https://jsfiddle.net/zvd5mLny/ Is your code different? – JoshG Jan 05 '19 at 11:02
  • I am trying to reproduce it right now in a smaller context but I am failing right now. Unfortunately I can't possibly post the whole original thing. Hopefully this helps me track down a more specific context that might be the source of the problem. I will update the question/provide a fiddle when/if I am successful. – Wolfone Jan 05 '19 at 11:09
  • Update: there is an event-handler attached that only calls stopPropagation() to the element. I think this is the source of the problem. See the fiddle I am going to attach to my post. This shows the behaviour. – Wolfone Jan 05 '19 at 12:19

0 Answers0