event bubbling and event capturing code example
Example 1: 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 2: bubbling in javascript
<script>
form.onclick = function(event) {
event.target.style.backgroundColor = '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>
Example 3: what is event bubbling in javascript with example
<div>1
<div>2
<div>3
<div>4
<div>5</div>
</div>
</div>
</div>
</div>
<button id="clear">clear output</button>
<section id="log"></section>
Example 4: what is event bubbling in javascript with example
var logElement = document.getElementById('log');
function log(msg) {
logElement.innerHTML += ('<p>' + msg + '</p>');
}
function capture() {
log('capture: ' + this.firstChild.nodeValue.trim());
}
function bubble() {
log('bubble: ' + this.firstChild.nodeValue.trim());
}
function clearOutput() {
logElement.innerHTML = "";
}
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', capture, true);
divs[i].addEventListener('click', bubble, false);
}
var clearButton = document.getElementById('clear');
clearButton.addEventListener('click', clearOutput);