1

I have a button appended to a parent button:

var parent_button = document.createElement("button");
var child_button = document.createElement("button");
parent_button.appendChild(child_button);

I want to create functionality for the child_button that's independent from that of the parent_button:

parent_button.onclick = function () {
  //do stuff
};

child_button.onclick = function () {
  //do some other stuff
};

But given this code, whenever I click on child_button, I am necessarily triggering parent_button.onclick(). How do I separate the two?

The overlapping buttons look like this:

enter image description here

shopofolive
  • 265
  • 3
  • 15
  • I appreciate this, @PHPglue. Just to clarify: when you say that buttons can't have children, are you saying that this is just bad coding practice, or that it's impossible to achieve in javascript/hmtl? If the latter, why is it that my child_button is successfully displayed within my parent_button? – shopofolive Nov 06 '17 at 02:39
  • i don't know if nested buttons are supposed to work but anyways you shouldn't do that. see [this](https://stackoverflow.com/questions/39386497/can-i-nest-button-inside-another-button). – sigh Nov 06 '17 at 03:51
  • @Phpglue is on the right track with how you should go about solving your problem. It is a bad coding practice, it would be easy to put two buttons inside of a container and then attached events to each perspective button. After all they are performing two separate actions. You code would be a lot more maintainable. You could easily swap out one the buttons for another element and it wouldn't break your code because it wouldn't be so tightly coupled to the parent button in the example you have given. – Larry Lane Nov 06 '17 at 04:00
  • I appreciate the advice, @larry-lane and karamarimo. I will refrain from nesting buttons in the future. The reason I wanted to do this has to do with spacing/alignment on my web page: it's less hassle to have a button with more stuff in it than to mess around with containers, labels, etc. I understand, though, that this is still not good enough reason to do what I'm doing. – shopofolive Nov 06 '17 at 14:48

1 Answers1

3

Use stopPropagation() on the event object of the child button. It will prevent the event from propagating from the child to the parent.

You can see an example here:

var pb = document.getElementById("pb");
var cb = document.getElementById("cb");
pb.addEventListener("click", function(e) {
  console.log("Parent");
});
cb.addEventListener("click", function(e) {
  console.log("Child");
  e.stopPropagation();
})
<button id="pb">Parent Button <button id="cb">Child Button</button></button>

Note: I think that the default behavior is that when you click on a child element, the event of both the child and the parent should trigger, but in this example, this doesn't happen; maybe it's something particular to buttons being parents.

Ammar Alyousfi
  • 4,112
  • 5
  • 31
  • 42