- What are event flows and event models in JS?
- A, events,
- 2. Event flow
- 3. Event flow model
- The event bubbling
- Event capture
- History of event flow model
- Five, the addEventListener ()
- AddEventListener () captures the presentation
- AddEventListener () bubble demo
- StopPropagation (
- Application of event flow model
- Advantages of event delegation
- JavaScript Events
What are event flows and event models in JS?
I’m participating in nuggets Creators Camp # 4, click here to learn more and learn together!
A, events,
Before we look at what a JS event flow is, let’s look at what a JS event is. Refer to the W3c explanation
An HTML event is something that happens on an HTML element
When using javaScript in HTML, javaScript can handle these events
To give some examples of common events:
- OnClick (mouse click element)
- Onmouseover (mouseover element)
- Onmouseout (mouse over element)
- Onkeydown (press the keyboard key)
- .
2. Event flow
Now that we know what an event is, what is a stream of events?
Let’s take it literally. Events we already know what they are. What about flows? Let’s take a look at Baidu’s explanation of streaming
Can we think of event flow as the order in which events are received from the page? These events are linked together to form a liquid whole, and the events in this whole have their own execution order. This is the event flow.
3. Event flow model
There are two more models in the event flow
Here we refer to a diagram to help us understand the event flow model
The event bubbling
When a node event is triggered, events of the same type are triggered from the inner circle to the outer circle div—body— HTML —document, all the way to the DOM root node
Event capture
When a node event is triggered, events of the same type are triggered from the DOM root node to the ancestor node until the current node itself is triggered. From the outer circle to the inner circle Document — HTML —body—div
History of event flow model
Event bubbling was introduced by IE, and event capture is an event stream concept introduced by Netscape.
ECMAScript later integrated the two models to create a unified standard: capture first in bubbling
The integrated standard event flow now has three phases:
- Event capture phase (target does not receive events during capture phase)
- Target phase (the execution phase of the event, which is referred to as the bubbling phase)
- Event bubbling phase (events return to Dom root node)
DOM2 events specify that no target-stage events are involved in the capture phase, but in IE9, Safari, Chrome, Firefox, Opera9.5 and later, events on the target event are triggered in the capture phase
Five, the addEventListener ()
The addEventListener() method is used to add an event handle to the specified element.
parameter | describe |
---|---|
event | Yes, a string specifying the event name |
function | Yes, specify the function to execute when the event is fired |
useCapture | Optional value that specifies whether the event is executed in the capture or bubble phase; 1. True: The event handle is executed in the capture phase; 2. -false — Default. Event handles are executed during the bubbling phase |
AddEventListener () captures the presentation
div >"btn1" style="height: 150px; width: 150px; background: red; color: #fff" btn1 div >"btn2" style="height: 100px; width: 100px; background: green; color: #fff" btn2 div >"btn3" style="height: 50px; width: 50px; background: blue; color: #fff" btn3 /div /div /div script let btn1 = document.getElementById('btn1') let btn2 = document.getElementById('btn2') let btn3 = document.getElementById('btn3') btn1.addEventListener('click'.function ( )< alert('btn1')>,true) btn2.addEventListener('click'.function ( )< alert('btn2')>,true) btn3.addEventListener('click'.function ( )< alert('btn3')>,true) /script Copy the code
Let’s see this code in action when we click on Btn3
Let’s see this code in action when we click on Btn2
Since the last parameter of addEventListener() is set to true, the entire execution is captured. Start at the current Dom root node and work up to the current node itself.
AddEventListener () bubble demo
It’s the same code, except here we change the last parameter of addEventListener() to false and set the execution to bubble.
Since the last argument to addEventListener() defaults to false(bubble), you can leave it at that
div >"btn1" style="height: 150px; width: 150px; background: red; color: #fff" btn1 div >"btn2" style="height: 100px; width: 100px; background: green; color: #fff" btn2 div >"btn3" style="height: 50px; width: 50px; background: blue; color: #fff"btn3/div /div /div script let btn1 = document.getElementById('btn1') let btn2 = document.getElementById('btn2') let btn3 = document.getElementById('btn3') btn1.addEventListener('click'.function ( )< alert('btn1')>,false) btn2.addEventListener('click'.function ( )< alert('btn2')>,false) btn3.addEventListener('click'.function ( )< alert('btn3')>,false) Copy the code
Let’s take a look at the execution
You can see that the execution sequence is to execute the node’s own events first, and then the same type of events of its ancestor nodes up to the Dom root node.
StopPropagation (
The stopPropagation() method prevents propagation of the same event from being called.
Propagation means bubbling up to the parent element or capturing down to the child element.
We use stopPropagation() function on Btn2
div >"btn1" style="height: 150px; width: 150px; background: red; color: #fff" btn1 div >"btn2" style="height: 100px; width: 100px; background: green; color: #fff" btn2 div >"btn3" style="height: 50px; width: 50px; background: blue; color: #fff"btn3/div /div /div script let btn1 = document.getElementById('btn1') let btn2 = document.getElementById('btn2') let btn3 = document.getElementById('btn3') btn1.addEventListener('click'.function ( )< alert('btn1')>,false) btn2.addEventListener('click'.function (event)< event.stopPropagation() alert('btn2')>,false) btn3.addEventListener('click'.function ( )< alert('btn3')>,false) /script Copy the code
Let’s take a look at the execution
You can see that when we click on btn3 we bubble up to btn2 and terminate
Application of event flow model
Event delegate, also called event delegate, refers to the use of event bubbling principle. You only need to add events to the outer parent container, and if the inner child element has a click event, it will bubble to the parent container. This is event delegate, simply put: child elements entrust their parent to execute events.
Where does this apply? Here’s an example:
ul li1/li li2/li li3/li li4/li li5/li /ul Copy the code
We now have a list where I want to listen for all of the
let ulDom = document.getElementsByTagName('ul') ulDom[0].addEventListener('click'.function(event)< alert(event.target.innerHTML) >) Copy the code
Let’s take a look at the implementation
As you can see, we have added click events to each
Advantages of event delegation
Let’s summarize the optimization of event delegation:
- Improved performance: Each function takes up memory, so adding an event handler to broker all events takes up less memory.
- Dynamic listener: Dynamically added elements can be automatically bound using event delegate, that is, new nodes can have the same events as other elements without being actively added.
JavaScript Events
In this article, I am going to discuss JavaScript Events with Examples. Please read our previous article where we discussed JavaScript Popup Boxes in detail. At the end of this article, you will understand the What are JavaScript Events and when and how to create and use Event Models in JavaScript with examples.
What is Event Model in JavaScript?
The DOM event model provides notifications for certain events. For example, execute a JavaScript function when a button is clicked. The DOM event model consists of events and event listeners attached to the DOM objects. For better understanding please have a look at the following image.
Event Types in JavaScript
- Mouse events – mouse clicks, mouse moves, mouse over, …
- Touch events – finger touch, touch start, end, move, …
- Form events – field focus, value change, form submit, …
- Keyboard events – key down, key up, keypress, …
- DOM / UI events – node insert, node remove, load, resize, …
Full list of all DOM event types will discuss later in our DOM events topic
Note: You may also define custom event types
Common Event Types in JavaScript:
Mouse events
- Click: When mouse is click on an element
- mouseup: When the mouse button is released over the element
- mousedown: When the mouse button is pressed over the element
- mouseover: When the cursor of the mouse comes over the element
- mouseout: When the cursor of the mouse leaves an element
DOM / UI events
- load: When the browser finishes the loading of the page
- unload: When the visitor leaves the current webpage, the browser unloads it
- reset: When the user clicks on the reset button on the form.
- select: When input text is selected
- resize: When the visitor resizes the window of the browser
- change: When the user modifies or changes the value of a form element
Touch events
- Touchstart: The touchstart event occurs when the user touches an element.
- touchend: The touchend event occurs when the user removes the finger from an element.
- touchcancel: The touchcancel event occurs when the touch event gets interrupted
- touchleave: The touchleave event is fired when a touch point is moved off the interactive area of an element.
- touchmove: The touchmove event occurs when the user moves the finger across the screen.
Note: The touchend event will only work on devices with a touch screen.
Keyboard events
- keydown: When user presses a key
- keypress: When user presses a key
- keyup: When the user released the key
Focus events
- Focus: When the user focuses on an element
- blur: When the user moves the focus away from a form element
- focusin: The focusin event fires when an element is about to receive focus
- focusout: The onfocusout event occurs when an element is about to lose focus
Event Handler Registration in JavaScript
In order to understand how to register event handler in JavaScript, please have a look at the following image.
How to Define JavaScript Event Handler in the HTML Code?
The JavaScript Event handling code can be specified in the HTML attributes such as onclick, onload, onmouseover, onresize, etc. To better understand, please have a look at the following image.
The JavaScript Event handling code can also be specified in the JavaScript code through the properties such as onclick, onresize,etc. In order to understand this better, please have a look at the below image.
Using addEventListener(…)
A more powerful way for attaching event handlers:
domElement.addEventListener(eventType, eventHandler, isCaptureEvent);
Here, isCaptureEvent: catch the “capture” or “bubbling” phase. Can attach multiple events in a chain
var button = document.getElementById("buttonOK"); button.addEventListener("click", function () < console.log("You clicked me"); >, false);
The “event” Object
The “event” object holds information about the event passed as parameter to the event handling function
btn.onclick = function (event)
- The type of the event (e.g. ‘click’, ‘resize’, …)
- The target of the event (e.g. the button clicked)
- The key pressed for keyboard events
- The mouse button / cursor position for mouse events
The “event” object is the only argument of the event handler
function onButtonClick(event) < console.log(event.target); console.log(event.type); console.log("(" + event.clientX + ", " + event.clientY + ")"); >button.addEventListener("click", onButtonClick, false);
Capturing and Bubbling Events
Browser Events Chain
When the user clicks on an HTML element. For example on a button in the page, the event is also fired on all of its parents.
The button is still the target. But the click event is fired on all of its parents. The click event is fired on all elements in the chain
JavaScript Event Chains: Types
domElement.addEventListener(eventType, eventHandler, isCaptureEvent)
Capturing handlers go down the chain
- The first executed handler is on the parent
- The last executed handler is on the target
In the next article, I am going to explain the Examples of Different JavaScript Events. Here, in this article, I try to explain JavaScript Events with examples. I hope this article will helps you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.