bubble event in javascript code example
Example 1: bubble sort javascript
bubbleSort(Array) {
let len = Array.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
if (Array[j] > Array[j + 1]) {
let tmp = Array[j];
Array[j] = Array[j + 1];
Array[j + 1] = tmp;
}
}
}
return Array;
};
Example 2: bubble sort javascript
function bubblesort(array) {
len = array.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len - i; j++) {
let a = array[j];
if (a != array[-1]) {
var b = array[j + 1];
if (a > b) {
array[j] = b;
array[j + 1] = a;
}
}
}
}
}
let array = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
bubblesort(array);
console.log(array)
Example 3: 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>
<!-- 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. -->
Example 4: 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 5: 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);