Javascript events understanding in a comprehensive way

Live URL

This is the JS code →

var containers = document.getElementsByClassName('container');
for (var i = 0, max = containers.length; i < max; i++) {
	containers[i].addEventListener('click', displayEventPhase, false);
}

function displayEventPhase(e) {
	var phase = e.eventPhase;

	if ( 1 === phase ) {
		phase = 'Capturing';
	} else if( 2 === phase ) {
		phase = 'At Target';
	} else if( 3 === phase ) {
		phase = 'Bubbling';
	}
	console.log( 'Box: ' + this.id + ' - ' + phase );
	// if (e.target.id === this.id) {
	// 	console.log( 'Box: ' + e.target.id + ' - ' + phase )
	// } 
}

On every click, it is giving bubbling phase, but not this one →

Where is the code is in a deviation?

The bubbling phase means that the click event occurred on a child, with one of its parents having the event listener. The event bubbled from that child element up through the other elements until it reached the event listener.

The target phase occurs when the event instead occurs on the actual element that has the event listener.

When it comes to event bubbling or capturing, I’ve found the following somewhat older information to be highly useful.

https://www.quirksmode.org/js/events_order.html

2 Likes

The third optional parameter useCapture on the addEventListener enables you to set whether to use capturing or bubbling.

I have added a click event listener for both the capturing and bubbling phase. I think this will give you the expected output

document
  .querySelectorAll('.container')
  .forEach(elem => {
    elem.addEventListener('click', displayEventPhase, false)
    elem.addEventListener('click', displayEventPhase, true)
  })
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.