Answer to "What is event bubbling/capturing?"

For reference, with examples, and

by Andrew Holloway

HTML

<div id="outer1">
  <div id="outer2">
    <div id="outer3">
      <a id="link" href="javascript:;">Click</a>
    </div>
  </div>
</div>

JavaScript

// bubbling happens from the innermost, outward. they occur after the capturing phase
document.querySelector('#outer1').addEventListener('click', function() {
	console.log('bubble div outer1 hit');
}, false);

document.querySelector('#outer2').addEventListener('click', function() {
	console.log('bubble div outer2 hit');
}, false);

document.querySelector('#outer3').addEventListener('click', function() {
	console.log('bubble div outer3 hit');
}, false);


// capturing happens first, and starts from outermost, inward
document.querySelector('#outer1').addEventListener('click', function() {
	console.log('capture div outer1 hit');
}, true);


document.querySelector('#outer2').addEventListener('click', function() {
	console.log('capture div outer2 hit');
}, true);


document.querySelector('#outer3').addEventListener('click', function() {
	console.log('capture div outer3 hit');
}, true);




// When added to the same element, they get run in the order they were added, regardless of the event handling type
document.querySelector('#link').addEventListener('click', function() {
	console.log('link capture');
}, true);

document.querySelector('#link').addEventListener('click', function() {
	console.log('link non-capture');
}, false);

// Try adding some `.preventDefault` calls in the code to see what impact they have on the logging messaging!