Event bubbling
Definition: When an event is triggered on an element, which is the same type of event will be on all the parent element is triggered, a process called event bubbling. This event is triggered from the original elements of the beginning has been bubbling to the DOM tree top.
Bubbling order: the original element -> parent element (s) -> body -> document -> window
As long as the parent element and the child element types registered the same event, when the event was a child element of the parent element of the triggering event will be triggered.
Q: event bubbling has always existed, why we can not easily be detected in the development of it?
A: Because there is no parent element registered to listen for the same type of event, that does not set the corresponding function is executed.
Commonly used methods to stop the event bubbling
- e.stopPropagation()
- Prevent further spread of the capture and bubbling phases in the current event.
- Most browsers support
- event.stopImmediatePropagation()
- If there are multiple events of the same type of event listener function to bind to the same element, when this type of event is triggered, they will be executed in the order added. If one listens to perform the function event.stopImmediatePropagation () method, the remaining elements of the current monitor function will not be executed.
- window.event.cancelBubble=true
- ie8 and below the browser
Event Listener sample code:
Example 1:
Click Xiaoming elements, in order to see the pop-up browser window: "I am Bob - yellow" ----> "I am the father - orange color" ----> "I'm a grandfather - red." Description Similar to listen event is triggered, the order is triggered from the parent element to the child element of the outer layer.
Example Two:
:( more commonly used event types event types, please refer MDN) https://developer.mozilla.org/zh-CN/docs/Web/Events
- click
- touch off
- touchmove
- touchEnd
- submit
- keydown
- …
Special events will not bubble:
- focus
- blur
Examples
When rolling with a car wash app drawer and select Home area Home page lists overlap, touch slide expanded area of the container, the touch event bubbling store in the end part of the list leads to the bottom of the list
Solution
In the drawer container to prevent the occurrence of a touch event (touchstart, touchmove, touchend, touchcancel) bubble in the end of the list.