How to have a different onClick event for the child element without affecting the parent one?
Asked Answered
L

2

2

Having the following structure:

<div class="the-parent">
  <div>
    <a onClick="doParentStuff()">
      <div>
        <i onClick="doChildStuff()"></i>
      </div>
    </a>
  </div>
</div>

Now, when the child element (icon) is clicked it logs the content of doChildStuff() but afterwards it also logs the content of doParentStuff().

Is there a way to call doChildStuff only when the icon is clicked and call doParentStuff when everything else inside the-parent div is clicked?

Lictor answered 15/12, 2022 at 13:30 Comment(3)
Inline event handlers like onclick are bad practice. They’re an obsolete, cumbersome, and unintuitive way to listen for events. Always use addEventListener instead. Then, utilize event delegation with closest and contains.Spire
Related: Javascript event delegation, handling parents of clicked elements?. composedPath can also be used. Make sure you’re aware of potential caveats of stopPropagation and read the documentation.Spire
I would suggest removing all onclick attributes, then adding this JS: addEventListener("click", ({ target }) => { const iElement = target.closest(".the-parent a i"), anchorElement = target.closest(".the-parent a"); if(iElement){ doChildStuff(); } else if(anchorElement){ doParentStuff(); } });. I’d also suggest reconsidering the usage of <a>. See Accessibility concerns of the <a> element.Spire
E
1

When the child is clicked, you must stopPropagation of the event:

function doChildStuff(e) {
  e.stopPropagation();
  console.log('child clicked');
}

function doParentStuff() {
  console.log('parent clicked');
}
<div class="the-parent">
  <div>
    <a onClick="doParentStuff()">
      <div>
        Test
        <button onClick="doChildStuff(event)">Child</button>
      </div>
    </a>
  </div>
</div>
Eversion answered 15/12, 2022 at 13:38 Comment(0)
T
2

Avoid the use of Event.stopPropagation() (unless you really, really know what you're doing).
An application, or third party code, should never stop or prevent an event to propagate throughout the application layers / components.
Instead, change your logic to implement a third function (like doStuff) that will trigger a desired function depending on the Event.target.closest() match

const doChildStuff = () => {
  console.log("child stuff");
};

const doParentStuff = () => {
  console.log("parent stuff");
};

const doStuff = (ev) => {
 if (!ev.target.closest(".icon")) {
    doParentStuff();
 }
 doChildStuff();
};

document.querySelectorAll(".anchor").forEach(elAnchor => {
  elAnchor.addEventListener("click", doStuff);
});
<div class="the-parent">
  <div>
    <a class="anchor">
      <div>
        Link
        <i class="icon">icon</i>
      </div>
    </a>
  </div>
</div>

Also, stop using HTML inline on* attribute handlers. Such code is hard to maintain and debug. JavaScript should be in one place only, and that's the respective tag or file. Use addEventListener instead.

Even if not asked, if you want to also separate the handler for the parent, simply put it into an else block:

const doChildStuff = () => {
  console.log("child stuff");
};

const doParentStuff = () => {
  console.log("parent stuff");
};

const doStuff = (ev) => {
  if (!ev.target.closest(".icon")) {
    doParentStuff();
  } else {
    doChildStuff();
  }
};

document.querySelectorAll(".anchor").forEach(elAnchor => {
  elAnchor.addEventListener("click", doStuff);
});
<div class="the-parent">
  <div>
    <a class="anchor">
      <div>
        Link
        <i class="icon">icon</i>
      </div>
    </a>
  </div>
</div>
Toothpick answered 15/12, 2022 at 13:56 Comment(5)
your code snippet doesn't work fine, it logs both messages when it should log only oneLictor
@LeoMessi but you asked that behavior only for the icon - which indeed respects the asked question requirement. If you click on the icon - only one log will be present instead of two.Toothpick
@LeoMessi otherwise the fix is simple as putting doChildStuff(); inside and else block: like: else { doChildStuff(); } . That's it.Toothpick
@LeoMessi sad to see another stopPropagation answer getting into account - teaching other people getting to this pages really bad coding habits :(Toothpick
Edited the answer to add that other example as well. @LeoMessiToothpick
E
1

When the child is clicked, you must stopPropagation of the event:

function doChildStuff(e) {
  e.stopPropagation();
  console.log('child clicked');
}

function doParentStuff() {
  console.log('parent clicked');
}
<div class="the-parent">
  <div>
    <a onClick="doParentStuff()">
      <div>
        Test
        <button onClick="doChildStuff(event)">Child</button>
      </div>
    </a>
  </div>
</div>
Eversion answered 15/12, 2022 at 13:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.