An overview of the

The browser’s event model responds to events through listener functions. After the event occurs, the browser listens for the event and executes the corresponding listener function. The following cases:

let div = document.getElementById('#div')
div.addEventListener('click'.() = >{
	console.log('Div is clicked')})Copy the code

We add listener events to div via addEventListener(). When the user clicks div, console.log(‘div was clicked ‘) is executed.

Event capture and event bubbling

<div class='grandfather'>
	<div class='father'>
		<div class='son'>The text</div>
	</div>
</div>
Copy the code

When we bind the click event to three divs at the same time, who exactly is clicked when the text is clicked?

It should be intuitive to think they’ve all clicked, but there’s a priority issue.

IE5 calls the event functions of descendant elements first, while Netscape calls the event functions of ancestor elements first.

That is:

  • Look for listener function from inside out, called event bubble (IE 5)

  • Looking for a listener function from the outside in, called event capture (Netscape)

The W3C eventually unified the standard, stating that browsers should support both call sequences. First, check whether there are functions listening according to the order of event capture, and then check whether there are functions listening according to the order of event bubble.

It is up to the developer to decide which event stream to choose.

.addEventListener('click',fn,bool)
Copy the code

If bool is not passed or falsy, it goes through the bubbling phase.

If the bool value is true, the capture phase is performed.