Learning the fourth edition of JavaScript Advanced Programming -- Chapter 17

Title: learning of the fourth edition of JavaScript advanced programming - Chapter 17
date: 2021-5-27 10:02:37
author: Xilong88
tags: JavaScript

Contents of this chapter:
Understanding event flow
Using event handlers
Understand different types of events
Possible interview questions:
1. Do you know the event flow?
2. Event bubbling? Event capture?
3. What are the methods of binding events?
4. What is the difference between target, currenttarget and this in the event?
5. What do you know about the new events in H5?
6. Event delegation?
7. What should be noticed about event performance problems?
8. What should I do to delete an event?
9. How to simulate events?

Summary: this chapter talks about events and the optimization of event performance

Knowledge points:

1. The interaction between JavaScript and HTML is realized through events, which represent a meaningful moment in the document or browser window. You can subscribe to events using listeners (also known as handlers) that execute only when the event occurs. In the field of traditional software engineering, this model is called "observer mode"

2. Event bubbling
IE event flow is called event bubbling because events are defined to trigger from the most specific element (the deepest node in the document tree) and then propagate upward to less specific elements (documents).

3. Event capture

It means that the least specific node should receive the event first, while the most specific node should receive the event last. Event capture is actually to intercept events before they reach the final target.

4.DOM event flow

The DOM2 Events specification specifies that the event flow is divided into three stages: event capture, reaching the target and event bubbling.


In the above figure, in the DOM event flow, the actual target (< div > element) will not receive events in the capture phase. This is because the capture phase ends from document to < HTML > and then to < body >. The next stage, the "reach the target" stage that triggers the event on the < div > element, is usually considered as part of the bubbling stage during event processing (discussed later). Then, the bubbling phase begins and the event propagates back to the document.

5. Event handler

The functions called in response to events are called event handlers (or event listeners).

<input type="button" value="Click Me" onclick="console.log('Clicked')"/>
<script>
  function showMessage() {
    console.log("Hello world!");
  }
</script>
<input type="button" value="Click Me" onclick="showMessage()"/>
<!-- output"click" -->
<input type="button" value="Click Me" onclick="console.log(event.type)">

Another interesting thing about dynamically created wrapper functions is that their scope chain has been extended. In this function, both the document and the members of the element itself can be accessed as local variables.

This is achieved by using with:

function() {
  with(document) {

    with(this) {
       // Attribute value
    }
  }
}

This means that event handlers can access their properties more easily. The following code has the same function as the previous example:

<!-- output"Click Me" -->
<input type="button" value="Click Me" onclick="console.log(value)">
<form method="post">
  <input type="text" name="username" value="">
  <input type="button" value="Echo Username"
         onclick="console.log(username.value)">
</form>
function() {
  with(document) {
    with(this.form) {
      with(this) {
         // Attribute value
      }
    }
  }
}

6.0 event handler

let btn = document.getElementById("myBtn");
btn.onclick = function() {
  console.log("Clicked");
};

The assigned function is treated as a method of elements. Therefore, the event handler will run in the scope of the element, that is, this is equal to the element. The following example demonstrates using this to reference the element itself:

let btn = document.getElementById("myBtn");
btn.onclick = function() {
  console.log(this.id);  // "myBtn"
};

By setting the value of the event handler property to null, you can remove the event handler added by DOM0, as shown in the following example:

btn.onclick = null;  // Remove event handler

7.2 event handling

addEventListener() and removeEventListener()

They receive three parameters: event name, event handler function and a Boolean value. true means to call the event handler in the capture phase and false (default) means to call the event handler in the bubble phase.

let btn = document.getElementById("myBtn");
btn.addEventListener("click", () => {
  console.log(this.id);
},

The main advantage of using DOM2 is that you can add multiple event handlers for the same event

let btn = document.getElementById("myBtn");
btn.addEventListener("click", () => {
  console.log(this.id);
}, false);
btn.addEventListener("click", () => {
  console.log("Hello world!");
}, false);

Use removeEventListener() and pass in the same parameters as when adding to remove. This means that anonymous functions added with addEventListener() cannot be removed

let btn = document.getElementById("myBtn");
btn.addEventListener("click", () => {
  console.log(this.id);
 }, false);
// Other codes
btn.removeEventListener("click", function() {    // No effect!
  console.log(this.id);

}, false);
let btn = document.getElementById("myBtn");
let handler = function() {
  console.log(this.id);
};
btn.addEventListener("click", handler, false);
// Other codes
btn.removeEventListener("click", handler, false);  // It works!

The function passed to remove must be the same as add.

8.attachEvent() and detachEvent()

IE implements a method similar to DOM

var btn = document.getElementById("myBtn");

btn.attachEvent("onclick", function() {
  console.log("Clicked");
});

The first parameter of attachEvent() is "onclick", not "click" of the addEventListener() method of DOM.

When using DOM0 mode, the value of this in the event handler is equal to the target element. When attachEvent() is used, the event handler runs in the global scope, so this is equal to window.

var btn = document.getElementById("myBtn");
btn.attachEvent("onclick", function() {
  console.log(this === window);   // true
});
var btn = document.getElementById("myBtn");
var handler = function() {
  console.log("Clicked");
};
btn.attachEvent("onclick", handler);
// Other codes
btn.detachEvent("onclick", handler);

9. Cross browser event handler

Custom addHandler() method

var EventUtil = {
  addHandler: function(element, type, handler) {
    if (element.addEventListener) {

      element.addEventListener(type, handler, false);
    } else if (element.attachEvent) {
      element.attachEvent("on" + type, handler);
    } else {
      element["on" + type] = handler;
    }
  },
  removeHandler: function(element, type, handler) {
    if (element.removeEventListener) {
      element.removeEventListener(type, handler, false);
    } else if (element.detachEvent) {
      element.detachEvent("on" + type, handler);
    } else {
      element["on" + type] = null;
    }
  }
};

10. Event object

When an event occurs in the DOM, all relevant information is collected and stored in an object named event.

DOM event object

let btn = document.getElementById("myBtn");
btn.onclick = function(event) {
  console.log(event.type);  // "click"
};
btn.addEventListener("click", (event) => {
  console.log(event.type);  // "click"
}, false);

Event objects generated by different events also contain different properties and methods. All event objects will contain these public properties and methods listed in the following table.


this object is always equal to the value of currentTarget, and target contains only the actual target of the event.

If the event handler is added directly to the
For the target of the graph, the values of this, currentTarget and target are the same.

let btn = document.getElementById("myBtn");
btn.onclick = function(event) {
  console.log(event.currentTarget === this);  // true
  console.log(event.target === this);         // true
};

In document Click handler added to body:

document.body.onclick = function(event) {
  console.log(event.currentTarget === document.body);              // true
  console.log(this === document.body);                             // true
  console.log(event.target === document.getElementById("myBtn"));  // true
};

this and currentTarget are both equal to document body
, because it is the element that registers the event handler. The target attribute is equal to the button itself, because that is the real target of the click event.

The type attribute is useful when a handler handles multiple events. For example, the following handler uses event type :

let btn = document.getElementById("myBtn");
let handler = function(event) {
  switch(event.type) {
    case "click":
      console.log("Clicked");
      break;
    case "mouseover":
      event.target.style.backgroundColor = "red";
      break;
    case "mouseout":
      event.target.style.backgroundColor = "";
      break;
  }
};
btn.onclick = handler;
btn.onmouseover = handler;
btn.onmouseout = handler;

The preventDefault() method is used to block the default action for a specific event

let link = document.getElementById("myLink");
link.onclick = function(event) {
  event.preventDefault();
};

For any event that can cancel the default behavior through preventDefault(), the cancelable property of the event object will be set to true.

The stopPropagation() method is used to immediately prevent the event flow from propagating in the DOM structure and cancel subsequent event capture or bubbling

The eventPhase property can be used to determine the current phase of the event flow.

If the event handler is called in the capture phase, eventPhase is equal to 1;

If the event handler is called on the target, eventPhase is equal to 2;

If the event handler is called during the bubbling phase, eventPhase is equal to 3.

IE event object

If the event handler is specified in DOM0 mode, the event object is only a property of the window object, as shown below:

var btn = document.getElementById("myBtn");
btn.onclick = function() {
  let event = window.event;
  console.log(event.type);  // "click"
};

If the event handler is specified using attachEvent(), the event object will be passed to the handler as a unique parameter, as shown below:

var btn = document.getElementById("myBtn");
btn.attachEvent("onclick", function(event) {
  console.log(event.type);  // "click"
});

11. Event type

DOM3 Events defines the following event types.

User interface events( UIEvent ): Involve and BOM Interactive general browser
 Pieces.
Focus event( FocusEvent ): Triggered when an element gains and loses focus.
Mouse event( MouseEvent ): Touch when using the mouse to perform certain actions on the page
 Hair.
Roller event( WheelEvent ): Touch when using the mouse wheel (or similar device)
Hair.
Input event( InputEvent ): Triggered when text is entered into a document.
Keyboard events( KeyboardEvent ): Use the keyboard to perform certain actions on the page
 Triggered when.
Composite event( CompositionEvent ): Using some kind of IME(Input
Method Editor,Triggered when characters are entered in the input method editor.

User interface events

DOMActivate : Triggered when the element is activated by the user through mouse or keyboard operation (ratio
click or keydown More general). This event happened in DOM3 Events China has been abolished
 Abandon. Do not use it because there are differences between browser implementations.
load : stay window Triggered when the page is loaded, the window cover
(<frameset> )Deceive all panes(<frame> )Triggered after loading,
stay<img> Triggered when the picture is loaded on the element<object> Elemental deception

Should be triggered after the object is loaded.
unload : stay window Triggered when the page is completely unloaded, install all windows on the window cover
 Triggered after the grid unloading is completed, and<object> When the corresponding object on the element is unloaded
 Trigger.
abort : stay<object> The element is terminated in advance by the user before the corresponding object is loaded
 Triggered when downloading is stopped.
error : stay window be fooled JavaScript Triggered when an error is reported<img> Element fooled
 Triggered when the specified picture cannot be loaded, in<object> The corresponding pair cannot be loaded when the element is cheated
 Image time trigger, which is triggered when one or more panes cannot be loaded on the window cover.
select : In the text box(<input> or textarea )The user was fooled into choosing a
 Triggered when one or more characters.
resize : stay window Triggered when a window or pane is zoomed.
scroll : Triggered on an element when the user scrolls an element that contains a scroll bar.<body>
Element contains the scroll bar of the loaded page.

load event

On the window object, the load event will be triggered after the entire page (including all external resources such as pictures, JavaScript files and CSS files) is loaded.
First kind

window.addEventListener("load", (event) => {
  console.log("Loaded!");
});

Second

<!DOCTYPE html>
<html>
<head>
  <title>Load Event Example</title>
</head>
<body onload="console.log('Loaded!')">
</body>
</html>

For backward compatibility, all browsers implement the load event on the window

The load event will also be triggered on the picture, including the picture in DOM and the picture in non dom. You can specify the location of the event directly to the onload attribute of the element in HTML
Management procedure:

<img src="smile.gif" onload="console.log('Image loaded.')">
let image = document.getElementById("myImage");
image.addEventListener("load", (event) => {
  console.log(event.target.src);
});

When creating a new < img > element through JavaScript, you can also specify an event handler to execute after loading. Here, the key is to specify the event handler before assigning the src attribute, as shown below:

window.addEventListener("load", () => {
  let image = document.createElement("img");
  image.addEventListener("load", (event) => {
    console.log(event.target.src);
  });
  document.body.appendChild(image);
  image.src = "smile.gif";
});

The following example uses a new Image object to realize Image preloading. It is not necessary to add the element to the document to download the Image. As long as the src attribute is set to it, the download will begin immediately

window.addEventListener("load", () => {
  let image = new Image();
  image.addEventListener("load", (event) => {
    console.log("Image loaded!");
  });
  image.src = "smile.gif";
});

unload event

The unload event is triggered after the document is unloaded

window.addEventListener("unload", (event) => {
  console.log("Unloaded!");
});
<!DOCTYPE html>
<html>
<head>
  <title>Unload Event Example</title>
</head>
<body onunload="console.log('Unloaded!')">
</body>
</html>

No matter how you use it, pay attention to the code in the event handler. Because the unload event is triggered after the page is unloaded, you cannot use objects that are only available after the page is loaded. At this point, accessing the DOM or modifying the appearance of the page will lead to an error.

resize event

The resize event is triggered when the browser window is scaled to a new height or width

scroll event
Although the scroll event occurs in the window, it actually reflects the changes of the corresponding elements in the page

window.addEventListener("scroll", (event) => {
  if (document.compatMode == "CSS1Compat") {
    console.log(document.documentElement.scrollTop);
  } else {
    console.log(document.body.scrollTop);
  }
});

focal event

blur : Triggered when an element loses focus. This event does not bubble, and all browsers are
 support.
DOMFocusIn : Triggered when the element gains focus. This event is focus Bubbling of
 Edition. Opera Is the only mainstream browser that supports this event. DOM3 Events Abandon
 Yes DOMFocusIn ,recommend focusin . 
DOMFocusOut : Triggered when an element loses focus. This event is blur General purpose of
 Edition. Opera Is the only mainstream browser that supports this event. DOM3 Events Abandon
 Yes DOMFocusOut ,recommend focusout . 
focus : Triggered when the element gains focus. This event does not bubble, and all browsers are
 support.
focusin : Triggered when the element gains focus. This event is focus Bubbling version of.
focusout : Triggered when an element loses focus. This event is blur General version of.

When the focus moves from one element to another in the page, the following events occur in turn.

(1) focuscout is triggered on an element that has lost focus.
(2) focusin is triggered on the element that gets the focus.
(3) blur is triggered on an element that has lost focus.
(4) DOMFocusOut is triggered on an element that has lost focus.
(5) focus is triggered on the element that gets the focus.
(6) DOMFocusIn is triggered on the element that gets focus.

Among them, the event targets of blur, DOMFocusOut and focusout are the elements that lose focus, while the event targets of focus, DOMFocusIn and focusin are the elements that get focus.

Mouse and wheel events

DOM3 Events defines 9 kinds of mouse events

click : Touch when the user clicks the mouse primary key (usually the left key) or presses the Enter key on the keyboard
 Hair. This is mainly based on the consideration of accessibility, so that the keyboard and mouse can be triggered
onclick Event handler.
dblclick : Triggered when the user double clicks the mouse primary key (usually the left key). This thing
 The piece is not in DOM2 Events Defined in, but well supported, DOM3
Events It is standardized.
mousedown : Triggered when the user presses any mouse button. This event cannot pass the key
 Disk trigger.
mouseenter : Touch when the user moves the mouse cursor from the outside of the element to the inside of the element
 Hair. This event does not bubble or touch when the cursor passes over a descendant element
 Hair. mouseenter The event is not in DOM2 Events Defined in, but DOM3
Events Event added in.
mouseleave : Touch when the user moves the mouse cursor from the inside of the element to the outside of the element
 Hair. This event does not bubble or touch when the cursor passes over a descendant element
 Hair. mouseleave The event is not in DOM2 Events Defined in, but DOM3
Events Event added in.
mousemove : Triggered repeatedly when the mouse cursor moves over the element. This event cannot be
 Triggered by keyboard.
mouseout : Touch when the user moves the mouse cursor from one element to another
 Hair. The element moved to can be the external element of the original element or the external element of the original element
 Child element. This event cannot be triggered from the keyboard.
mouseover : Triggered when the user moves the mouse cursor from the outside of the element to the inside of the element.
This event cannot be triggered from the keyboard.
mouseup : Triggered when the user releases the mouse button. This event cannot be touched through the keyboard
 Hair.

Except mouseenter and mouseleave, all mouse events will bubble and can be cancelled, which will affect the default behavior of the browser.

The default relationship between events will also affect the behavior of other events.

The premise of the click event is that after the mousedown event is triggered, the mouseup event is triggered on the same element. If either of the mousedown and mouseup events is canceled, the click event will not be triggered. Similarly, two consecutive click events cause the dblclick event to trigger. The dblclick event will not occur as long as any logic prevents the two click events from happening (such as canceling one of the click events or canceling either of the mousedown or mouseup events).

Order:

(1) mousedown
(2) mouseup
(3) click
(4) mousedown
(5) mouseup
(6) click
(7) dblclick

Client coordinates
Mouse events occur somewhere in the browser viewport. This information is stored in the clientX and clientY properties of the event object.

let div = document.getElementById("myDiv");
div.addEventListener("click", (event) => {
  console.log(`Client coordinates: ${event.clientX}, ${event.clientY}`);
});

Page coordinates
The client coordinates are the coordinates of the mouse cursor in the client viewport when the event occurs, while the page coordinates are the coordinates of the mouse cursor on the page when the event occurs, which can be obtained through pageX and pageY of the event object.

These two attributes represent the position of the mouse cursor on the page, so they reflect the distance from the cursor to the page rather than the left and top of the viewport.

let div = document.getElementById("myDiv");
div.addEventListener("click", (event) => {
  console.log(`Page coordinates: ${event.pageX}, ${event.pageY}`);
});

Screen coordinates

Mouse events occur not only in the browser window, but also on the whole screen. You can get the mouse cursor through the screenX and screenY properties of the event object
Coordinates on the screen.

The screen coordinates of mouse events can be obtained as follows:

let div = document.getElementById("myDiv");
div.addEventListener("click", (event) => {
  console.log(`Screen coordinates: ${event.screenX}, ${event.screenY}`);
});

Modifier key

Although mouse events are mainly triggered by the mouse, sometimes the state of keyboard keys should be considered to determine the operation that the user wants to achieve. The modifier keys Shift, Ctrl, Alt, and Meta on the keyboard are often used to modify the behavior of mouse events.

DOM specifies four attributes to represent the status of these modifier keys: shiftKey, Ctrl key, altKey and metaKey. These attributes will contain the Boolean value true when the corresponding modifier key is pressed and false when it is not pressed. When a mouse event occurs, these attributes can be used to detect whether the modifier key is pressed.

let div = document.getElementById("myDiv");
div.addEventListener("click", (event) => {
  let keys = new Array();
  if (event.shiftKey) {
    keys.push("shift");
  }
  if (event.ctrlKey) {
    keys.push("ctrl");
  }
  if (event.altKey) {
    keys.push("alt");
  }
  if (event.metaKey) {
    keys.push("meta");
  }
  console.log("Keys: " + keys.join(","));
});

Mouse button

The click event is triggered only when the mouse key is clicked on the element (or the Enter key on the keyboard is pressed), so the key information is not required.

For mousedown and mouseup events, there will be a button attribute on the event object, indicating press
Which key is pressed or released.

DOM defines three values for this button attribute:
0 indicates mouse primary key
1 indicates the middle mouse button (usually also the wheel button)
2 indicates the secondary mouse button.

By convention, the primary key of the mouse is usually the key on the left, and the secondary key is usually the key on the right

mousewheel event

document.addEventListener("mousewheel", (event) => {
  console.log(event.wheelDelta);
});

wheelDelta
When the mouse wheel rolls forward, wheelDelta is + 120 each time;
When the mouse wheel scrolls backward, the wheelDelta is – 120 each time;

12. Keyboard and input events

Keyboard events include 3 events:
keydown ,It is triggered when the user presses a key on the keyboard, and it will be triggered repeatedly if it is continuously pressed.
keypress ,It is triggered when the user presses a key on the keyboard and generates characters, and it will be triggered repeatedly if it is continuously pressed. Esc Key will also trigger this event. DOM3 Events Abandoned
keypress Events, and recommendations textInput event.
keyup ,Triggered when the user releases a key on the keyboard.

Each key has a key code, which can be checked.
The value of keyCode is consistent with the ASCII encoding of lowercase letters and numbers

There are many events that need not be completely recorded. You can use them and check them again.

HTML5 events

contextmenu event

Specifically used to indicate when the context menu should be displayed, allowing developers to cancel the default context menu and provide custom menus.

The contextmenu event bubbles, so you can handle all similar events on the page as long as you specify an event handler for the document.

<!DOCTYPE html>
<html>
<head>
  <title>ContextMenu Event Example</title>
</head>
<body>
  <div id="myDiv">Right click or Ctrl+click me to get a custom context menu.
    Click anywhere else to get the default context menu.</div>
  <ul id="myMenu" style="position:absolute;visibility:hidden;background-color:
    silver">
    <li><a href="http://www.somewhere.com"> somewhere</a></li>
    <li><a href="http://www.wrox.com">Wrox site</a></li>
    <li><a href="http://www.somewhere-else.com">somewhere-else</a></li>
  </ul>
</body>
</html>
window.addEventListener("load", (event) => {
  let div = document.getElementById("myDiv");
  div.addEventListener("contextmenu", (event) => {
    event.preventDefault();
    let menu = document.getElementById("myMenu");
    menu.style.left = event.clientX + "px";
    menu.style.top = event.clientY + "px";
    menu.style.visibility = "visible";
  });
  document.addEventListener("click", (event) => {
    document.getElementById("myMenu").style.visibility = "hidden";
  });
});

beforeunload event

The beforeunload event will be triggered on the window, which is intended to provide an opportunity for developers to prevent the page from being unloaded.

window.addEventListener("beforeunload", (event) => {
  let message = "I'm really going to miss you if you go.";
  event.returnValue = message;
  return message;
});

DOMContentLoaded event

The DOMContentLoaded event will be triggered immediately after the DOM tree is built, instead of waiting for images, JavaScript files, CSS files or other resources to be loaded. Compared with the load event, DOMContentLoaded allows developers to specify event handlers while downloading external resources, so that users can interact with the page faster.

document.addEventListener("DOMContentLoaded", (event) => {
  console.log("Content loaded");
});

readystatechange event

Each object that supports readystatechange events
Each has a readyState attribute that has one of the possible string values listed below.

uninitialized: the object exists and has not been initialized.
Loading: the object is loading data.
loaded: the object has finished loading data.
interactive: the object can interact, but it has not been loaded yet.
Complete: object loading is complete.

pageshow and pagehide events

hashchange event

HTML5 adds a hashchange event to notify developers when the URL hash value (the last # part of the URL) changes. This is because developers often use URL hash values to store status information or route navigation information in Ajax applications.

The onhashchange event handler must be added to the window and called every time the URL hash value changes. The event object has two new properties: oldURL and newURL. These two properties save the URL before and after the change, and are the complete URL containing the hash value. The following example shows how to get the URL before and after the change:

window.addEventListener("hashchange", (event) => {
  console.log(`Old URL: ${event.oldURL}, New URL: ${event.newURL}`);
});

If you want to determine the current hash value, you'd better use the location object:

window.addEventListener("hashchange", (event) => {
  console.log(`Current hash: ${location.hash}`);
});

Device events
Check it when you use it

13. Memory and performance

Event delegation:
The solution to excessive event handlers is to use event delegates. Event delegates take advantage of event bubbling and can use only one event handler to manage one type of event.

<ul id="myLinks">
  <li id="goSomewhere">Go somewhere</li>

  <li id="doSomething">Do something</li>
  <li id="sayHi">Say hi</li>
</ul>

The HTML here contains three list items, which should be performed when clicked. In this regard, the common practice is to specify three event handlers like this:

let item1 = document.getElementById("goSomewhere");
let item2 = document.getElementById("doSomething");
let item3 = document.getElementById("sayHi");
item1.addEventListener("click", (event) => {
  location.href = "http:// www.wrox.com";
});
item2.addEventListener("click", (event) => {
  document.title = "I changed the document's title";
});
item3.addEventListener("click", (event) => {
  console.log("hi");
});

Using event delegation, you can solve the problem by adding an event handler to the common ancestor node of all elements. For example:

let list = document.getElementById("myLinks");
list.addEventListener("click", (event) => {
  let target = event.target;
  switch(target.id) {
    case "doSomething":
      document.title = "I changed the document's title";
      break;
    case "goSomewhere":
      location.href = "http:// www.wrox.com";
      break;

    case "sayHi":
      console.log("hi");
      break;
  }
});

Event delegation has the following advantages.

The document object is always available, and you can add event handlers to it at any time (without waiting for DOMContentLoaded or load events). This means that as long as the page renders clickable elements, it can work without delay.

Save time on setting up page event handlers. Specifying only one event handler saves both DOM references and time.

Reduce the memory required for the whole page and improve the overall performance.

Delete event handler

Delete element with event handler

<div id="myDiv">
  <input type="button" value="Click Me" id="myBtn">
</div>
<script type="text/javascript">
  let btn = document.getElementById("myBtn");
  btn.onclick = function() {
    // Perform operations
    document.getElementById("myDiv").innerHTML = "Processing...";
    // No!
  };
</script>
<div id="myDiv">
  <input type="button" value="Click Me" id="myBtn">
</div>
<script type="text/javascript">
  let btn = document.getElementById("myBtn");
  btn.onclick = function() {
    // Perform operations
    btn.onclick = null;   // Delete event handler
    document.getElementById("myDiv").innerHTML = "Processing...";
  };

</script>

This ensures that memory is recycled and that buttons can be safely deleted from the DOM.

If the event handlers are not cleaned up after the page is unloaded, they will still remain in memory.

In general, it is best to delete all event handlers in the onunload event handler before the page is unloaded. At this time, it can also reflect the advantages of using event delegation. Because there are few event handlers, it is easy to remember what to delete. One thing to remember about cleaning up when unloading a page is that what is done in the onload event handler is best recovered in the onload event handler.

14. Simulated events

At any time, you can use document The createevent () method creates an event object. This method receives a parameter, which is a string representing the type of event to be created.

let btn = document.getElementById("myBtn");
// Create event object
let event = document.createEvent("MouseEvents");
// Initialize event object
event.initMouseEvent("click", true, true, document.defaultView,
                     0, 0, 0, 0, 0, false, false, false, false, 0, null);

// Trigger event
btn.dispatchEvent(event);
let textbox = document.getElementById("myTextbox"),

    event;
// Create the event object in the way of DOM3
if (document.implementation.hasFeature("KeyboardEvents", "3.0")) {
   event = document.createEvent("KeyboardEvent");
   // Initialize event object
   event.initKeyboardEvent("keydown", true, true, document.defaultView, "a",
                           0, "Shift", 0);
}
// Trigger event
textbox.dispatchEvent(event);

That is, it can simulate the occurrence of some events

Custom DOM events

DOM3 adds a custom event type. Custom events do not trigger native DOM events, but allow developers to define their own events. To create a custom event, you need to call createEvent("CustomEvent"). The returned object contains the initCustomEvent() method, which receives the following four parameters.

Type (string): the type of event to trigger, such as "myevent". Bubbles (Boolean): indicates whether the event bubbles.
cancelable (Boolean): indicates whether the event can be cancelled. Detail: any value. As the detail attribute of the event object.

Custom events can be distributed in the DOM like other events, such as:

let div = document.getElementById("myDiv"),
    event;
div.addEventListener("myevent", (event) => {
  console.log("DIV: " + event.detail);
});
document.addEventListener("myevent", (event) => {
  console.log("DOCUMENT: " + event.detail);
});
if (document.implementation.hasFeature("CustomEvents", "3.0")) {
  event = document.createEvent("CustomEvent");
  event.initCustomEvent("myevent", true, false, "Hello world!");
  div.dispatchEvent(event);
}

Keywords: Javascript Front-end ECMAScript

Added by kwilder on Tue, 08 Feb 2022 12:00:05 +0200