Basic event stopPropagation() example - a better way of doing so? I've got a very very basic demo here that uses the .stopPropagation method. I want to just make it so that clicking on the parent element only runs the function, so I assumed I could use e.stopPropagation() as in the commented out line in the example below. However, that fails, which meant I had to apply the stopPropagation() method to the child element to prevent clicking on the child activating the initial click function.
Is this really the right way of doing this, or is there a better way? Something doesn't feel right here. Thanks for any help - the code is below


var test = document.getElementById('test'),
    child = document.getElementById('child');

test.addEventListener('click', function (e) {
  //e.stopPropagation();
  console.log('click');
});

child.addEventListener('click', function (e) {
  e.stopPropagation();
  console.log('clicked child - is there a better way of using e.stopPropagation() ?');
});
#test {
  background: red;
  display: flex;
  position: relative;
  height: 30px;
  width: 100%;
}
#child {
  background: pink;
  margin-top: 5em;
  position: absolute;
}
&lt;div id='test'&gt;
  &lt;div id='child'&gt;child&lt;/div&gt;
&lt;/div&gt;



CodePen: https://codepen.io/ns91/pen/wvayqaE
Your Question

Is this really the right way of doing this, or is there a better way? Something doesn't feel right here.

The term &quot;better&quot; is subjective so you can judge for yourself. Presuming there is not a need to have clicks on the child elements trigger any event handlers, one alternative is to use the CSS property pointer-events style. One could use the value none:

none
The element is never the target of pointer events; however, pointer events may target its descendant elements if those descendants have pointer-events set to some other value. In these circumstances, pointer events will trigger event listeners on this parent element as appropriate on their way to/from the descendant during the event capture/bubble phases.



var test = document.getElementById('test'),
    child = document.getElementById('child');

test.addEventListener('click', function (e) {
  console.log('click on parent without stopping propagation');
});
#test {
  background: red;
  display: flex;
  position: relative;
  height: 30px;
  width: 100%;
}
#child {
  background: pink;
  margin-top: 5em;
  position: absolute;
  pointer-events: none;
}
&lt;div id='test'&gt;
  &lt;div id='child'&gt;child&lt;/div&gt;
&lt;/div&gt;