javascriptstoppropagation

How do I prevent event propagation on link click?


When I click on my a-tag, I do not want the parent's event to trigger. If the child had a normal event listener, it could be prevented by event.stopPropagation(), but how do I do it when there is no "event"?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="parent" style="width:100px; height:100px; background-color: red">
    <a id="child" href="https://i.kym-cdn.com/entries/icons/facebook/000/013/564/doge.jpg">Text</a>
</div>
<script>
    document.getElementById("parent").addEventListener("click", function () {
        alert("Oh no, you clicked me!");
    });
</script>
<script src="test.js"></script>
</body>
</html>

Solution

  • Approach 1

    If the child had a normal event listener, it could be prevented by event.stopPropagation()

    Yes.

    but how do I do it when there is no "event"?

    There is an event. You are just not listening for it.

    You could solve the problem by listening on the child element:

    document.getElementById("parent").addEventListener("click", function() {
      alert("Oh no, you clicked me!");
    });
    
    document.querySelector("a").addEventListener("click", function(e) {
      e.stopPropagation();
    });
    <div id="parent" style="width:100px; height:100px; padding: 1em; background-color: #aaa">
      <a id="child" href="https://placeimg.com/200/200/nature/sepia">Text</a>
    </div>


    Approach 2

    Alternatively, you could check the target of the event and see if it is unacceptable.

    const blacklist = [document.querySelector("a")];
    
    document.getElementById("parent").addEventListener("click", function(e) {
      if (blacklist.includes(e.target)) {
        return;
      }
      alert("Oh no, you clicked me!");
    });
    <div id="parent" style="width:100px; height:100px; padding: 1em; background-color: #aaa">
      <a id="child" href="https://placeimg.com/200/200/nature/sepia">Text</a>
    </div>