2

I hope this might be a low-hanging fruit for all you web-dev experts out there:

I have implemented event delegation by attaching a mouse click handler to a parent element of an unordered list of anchor elements (classic navigation design). The document I am working on exists in an iFrame. The handler looks like this:

const handleMouseClick = function(evt) {
            if (evt.target.matches('a')) {
                evt.preventDefault();
                evt.stopPropagation();
                console.log('Clicked a tag....', event.target.href);
            }
};

Just to provide a full context, I am clicking through an overlay element that takes no pointer events - so it should have no influence on click handling.

Anyway, when clicking on one of the anchor tags, I would like to prevent the iframe from loading the URL referenced in the anchor. The before mentioned click handler, which is attached to a parent, receives the click event just fine and I would have expected that calling event.preventDefault() would do the trick. However, I have to call both event.preventDefault() and event.stopPropagation() to stop the iframe from loading the link. If I remove either one of them, the iframe loads the link?

My first thought on this is that this is unexpected, when looking at the literature on preventDefault and stopPropagation but I might be missing something. What am I missing - why is event.preventDefault() not sufficient in this case?

Stephen Miller
  • 503
  • 3
  • 11
  • I [can't reproduce](https://jsfiddle.net/hrgz21bx/) the issue .? Maybe you should add a [mre] to your question? – Teemu May 30 '21 at 16:15
  • Thanks. I will see if I can come up with a minimal reproducible example, but I have to extract from a rather large context and it is easy to miss the source of the issue when doing that. If I succeed, I will post an update. Luckily, since I have found a way to get the effect I was after, it is not mandatory for me, but I would like to know why the expected behavior is not seen in this case - for future references. – Stephen Miller May 30 '21 at 17:02

0 Answers0