The event

The interaction between Js and HTML is accomplished through events, which are specific moments of interaction that occur in a document or browser window. There are many categories of event types, such as DOM event type, focus event type, scroll event type, and so on

Flow of events

The event bubbling

Events bubble. Events start from specific nodes and gradually bubble up to outer nodes. For example, when we click on div with ID a, the event will be passed up a=> b => c, and when we click click, the event will be output 123 in turn

<div id='c' onclick='console.log(3)'>
    <div id='b' onclick='console.log(2)'>
        <div id='a' onclick='console.log(1)'>
            click
        </div>
 </div> </div> Copy the code

Event capture

While event capture is the only event-flow model supported by Netscape, IE9, Safari, Chrome, Opera, and Firefox all currently support this event-flow model. Although the “Dom2-level Events” specification requires that events should propagate from a Document object, these browsers capture events from a Window object. Event capture is rarely used because older browsers do not support it.

The DOM event flow

DOM event flow is divided into three stages: capture stage, target stage and bubble stage. DOM event flow is divided into DOM0 level and DOM2 level.

Dom0-level event handler

Dom0-level events, such as click, load, and so on, are considered methods of the element, so this is the element itself, and its scope is also the current target element.

<div id='a' onclick='console.log(this.id)'>
    click
</div>
Copy the code

The printed “this” is the element itself. Clear DOM0 events by assigning them to NULL.


target.onclick = null

Copy the code

Dom2-level event handler

Dom2-level events provide two methods, the well-known addEventListener and removeEventListener. They all provide three arguments: event name, event method, and whether the event is executed in the capture phase or in the bubble phase. The Boolean value is true in the capture phase and false in the bubble phase. The default is False

addEventListener

var target = document.getElementById('a')
target.addEventListener('click'.function () {
    console.log(this.id)
}, false)
Copy the code

DOM2 level events do not conflict with DOM0 level events, so when click. This will be printed first, followed by the ID, and you can add more than one click event. In this case, the ID will be printed first, and the hello World will be printed in the same order as the hello World was added

var target = document.getElementById('a')
target.addEventListener('click'.function () {
    console.log(this.id)
}, false)

target.addEventListener('click'.function () {  console.log('hello world') }, false) Copy the code

Event priority: DOM0 event > DOM2 A simple interview question, click C output ABC and output CBA

<div id="a">
    a
    <div id="b">
        b
        <div id="c">
 c  </div>  </div> </div> Copy the code

removeEventListener

To remove an event, you must take two parameters, the event name and the handler. The function must be the same, otherwise it cannot be removed.

var target = document.getElementById('a')
function sayHello () {
    console.log('hello world')
}
target.addEventListener('click', sayHello, false)
 target.removeEventListener('click'.function () {  console.log('hello world') }, false) // Invalid cannot be removed  target.removeEventListener('click', sayHello, false) / / effective Copy the code

IE implements two methods similar to those in DOM :attachEvent() and detachEvent(). Both methods take the same two arguments: the event handler name and the event handler function. Because IE8 and earlier only support event bubbling, event handlers added via attachEvent() are added to the bubbling phase.

In view of this, it encapsulates a small event handling method that can be used cross-platform:

var EventUtil = {
  addHandler: function(element, type, handler, isBubble = false) { 
    if (element.addEventListener){
      element.addEventListener(type, handler, isBubble);
    } else if (element.attachEvent){
 element.attachEvent("on" + type, handler);  } else {  element["on" + type] = handler;  }  },  removeHandler: function(element, type, handler, isBubble = false){  if (element.removeEventListener){  element.removeEventListener(type, handler, isBubble);  } else if (element.detachEvent){  element.detachEvent("on" + type, handler);  } else {  element["on" + type] = null;  }  } }; Copy the code

The event object

Both DOM0 and DOM2 will return an Event object when they execute an Event. There are a lot of properties, but let’s focus on the following.

1. PreventDefault, cancel the default action, for example, skip to label A; The related attribute is cacelable. You can use preventDefault to cancel the default. Set cacelable to true, otherwise set it to false

2. What type of event, such as click, starts the behavior

3. EventPhase Indicates the current phase in which the event is triggered, whether it is the bubble, capture, or target phase

4. StopPropagation can stop the continuous transmission of bubble and capture

5. SrcElement, like target, is the target object of the event

Custom event

In addition to the usual use of native events, sometimes custom events are required. There are two ways to create custom events, the Event() constructor and the CustomEvent() constructor, and the createEvent() is deprecated, but it’s still supported by the browser, so we’ll leave it alone for now, so you can see for yourself.

Event()

Two parameters are supported: 1. TypeArg Event name 2. EventInitOption Initial configuration of the event, which contains three fields

parameter type instructions
bubbles Boolean Indicates whether the event bubbles
cancelable Boolean Indicates whether the event can be cancelled
composed Boolean Indicates whether an event fires a listener outside the shadow DOM root node.

ex:

// Create event
const ev = new Event('testEvent')
// Listen for events
document.addEventListener('testEvent'.function () {
    console.log('testEvent executed ')
}) // Triggers the event document.dispatchEvent(ev) Copy the code

CustomEvent()

Two parameters are supported: 1. TypeArg event name 2. EventInitOption Initial configuration of the event

// Create event
const ev = new CustomEvent('testEvent', {
  detail: {
    extraParams: 1
  }
}) // Listen for events document.addEventListener('testEvent'.function (e) {  console.log('testEvent executed ', e.detail) }) // Triggers the event document.dispatchEvent(ev) Copy the code

The event agent

Event proxy: The event of the child element is transmitted to the parent element in the form of bubbling. General application:

 <div id="idd">
    <div>
      <section>
        <div>1</div>
        <div>1</div>
 <div>1</div>  <div>1</div>  <div>1</div>  <div>1</div>  <div>1</div>  <div>1</div>  <div>1</div>  <div>1</div>  <div>1</div>  <div>1</div>  </section>  </div>  </div> Copy the code
function findParent (child, parent) {
  if (child.parentNode === parent) {
    return true
  } else {
    if(child.parentNode.nodeName.toLowerCase ! = ='html') {
 findParent(child.parentNode, parent)  } else {  return false  }  } }  window.onload = function () {  const parent = document.getElementById('idd')  parent.onclick = function (e) {  let flag = findParent(e.target, parent)  if (e.target.nodeName.toLowerCase() === 'div' && flag) {  console.log('div')  }  } } Copy the code

All of this allows us to reduce DOM manipulation and improve performance, and we find that this code has a lower upfront cost because only one DOM element is retrieved and only one event handler is added. Although the end result is the same for the user, this technique requires less memory. All events that use buttons (most mouse and keyboard events) are suitable for the event delegate technique.

Finally, there are too many types of events to use with varying degrees of difficulty; There are some memory and performance issues to consider when using events.

1. It is necessary to limit the number of event handlers on a page. Too many will consume a lot of memory and make the page feel less responsive to users. 2. The event delegate technology based on the event bubble mechanism can effectively reduce the number of event handlers. 3. You are advised to remove all event handlers from the page before the browser uninstalls the page. </p>Copy the code

There are mistakes or deficiencies welcome corrections.