Click, scroll, touch, drag… The way users interact with web pages can be called “events,” and understanding JavaScript’s event mechanism can be very helpful in optimizing some user interactions or dealing with online bugs.

Without further discussion, the “events” triggered by user interaction can be divided into the following stages 👇

  • Capture phase: Events fromwindowObject starts firing, from the top down to the target object
  • Target phase: Events are fired on the target object
  • Bubbling phase: Events work from the target object, first on the target itself, from the bottom up to the outermost layerHTMLThe element

How to turn on bubble & capture?

The triggering phase of an event has already been covered, so how do you use bubbling and capturing separately during actual coding? In fact, addEventListener provides bubblingevents by default. Assuming you want to enable capture, you can simply set it like this:

// The code is for reference only
const el = document.querySelector('div');
el.addEventListener('click'.function(e) {
    console.log('test');
}, true)
Copy the code

Of course, addEventListener also provides a more detailed optional configuration 👇

Other pit

Next, let’s look at a demo 👇

HTML code 👇

<div class="container">
	<div class="content">
		<! -- Enough text for the content div to appear in the scroll bar -->
	</div>
</div>
Copy the code

JavaScript code 👇

const el = document.querySelector('container');
el.addEventListener('scroll'.function(e){
	console.log('scroll');
});
Copy the code

When you run it, you’ll notice that no matter how much text you scroll through the content, no log is printed, so the content doesn’t bubble up when it scrolls? !!!!!

In fact, there are some events that do not have a “bubbling phase,” and scroll is one of them. The “bubbling phase” can only be used on document or Window, otherwise the “capture phase” can only be used.

If you look up the documentation on MDN, there is no mention of this, and the scroll event is highlighted as bubbling 👇

Instead, there is a hint of bubbling stage, but if you switch to the traditional Chinese version of the words on the embarrassment 😅

Does not bubble on the element, but bubbles on the Document and window.

Notice that the default view mentioned here is actually document.defaultView, and the return value is Window.

In other words, for the Scroll event, it’s bubbling from the Document to the window object.

conclusion

  • After an event is generated, there are generally three phases, namely “capture phase”, “target object” and “bubble phase”. But not all events necessarily have a “bubbling phase,” for examplescrollEvents or other media types of events
  • MDNThe document is not very accurate, it is best to compare the differences between different language versions when searching the document (also related to the translation of the document, may be smuggled 😄)

reference

Bubbling and capturing

scroll