how to stop event bubbling in javascript code example

Example 1: stop propagation event

$("span").click(function(event){
  event.stopPropagation();
  alert("The span element was clicked.");
});
$("p").click(function(event){
  alert("The p element was clicked.");
});
$("div").click(function(){
  alert("The div element was clicked.");
});

Example 2: javascript event stoppropagation

event.stopPropagation();

Example 3: how to prevent event capturing in javascript

how to prevent event button click capturing to tag/div/icon
easiest way OPTION 1 with CSS:
button > * {
  pointer-events: none;
}

OPTION 2 with javascript:
use e.currentTarget.children ;

OPTION 3 with Javascript:
use e.target.closest('selector') to locate the child, not e.currentTarget;

Example 4: bubbling in javascript

<script>
	form.onclick = function(event) {
  event.target.style.backgroundColor = 'yellow';

  // chrome needs some time to paint yellow
  setTimeout(() => {
    alert("target = " + event.target.tagName + ", this=" + this.tagName);
    event.target.style.backgroundColor = ''
  }, 0);
};
</script>
<html>
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="example.css">
</head>

<body>
  A click shows both <code>event.target</code> and <code>this</code> to compare:

  <form id="form">FORM
    <div>DIV
      <p>P</p>
    </div>
  </form>
</body>
</html>

<!-- A handler on a parent element can always get the details about where it actually happened.

The most deeply nested element that caused the event is called a target element, accessible as event.target.

Note the differences from this (=event.currentTarget):

event.target – is the “target” element that initiated the event, it doesn’t change through the bubbling process.
this – is the “current” element, the one that has a currently running handler on it.
For instance, if we have a single handler form.onclick, then it can “catch” all clicks inside the form. No matter where the click happened, it bubbles up to <form> and runs the handler.

In form.onclick handler:

this (=event.currentTarget) is the <form> element, because the handler runs on it.
event.target is the actual element inside the form that was clicked. -->