Wechat official account: [Dafront-end Yizhan] Follow Dafront-end Yizhan. Questions or suggestions, please leave a message on our official account.

Event bubbling and event capture

<! DOCTYPE HTML > < HTML > <body> <div id="myDiv"> Click </div> </body> </ HTML >Copy the code

The event bubble starts with the most specific element (the deepest node in the document tree) and propagates up to the less specific element (the document). Click on the

element in the above code first fires a Click event, which then fires on each node as it moves up the DOM tree. Until the Document object is reached

The node with the least specific event capture should receive the event first, while the node with the most specific event capture should receive the event last. Event capture is really about intercepting an event before it reaches its final destination. In the code above, click on the

element, reaching the Document element first and the

element last

Event handlers

An event means that the user or browser performs some kind of action. For example, click, load, mouseover. Functions called in response to events are called event handlers (or event listeners)

<form method="post"> 
 <input type="text" name="username" value=""> 
 <input type="button" value="Echo Username" 
 onclick="console.log(username.value)"> 
</form>
Copy the code

In this example, clicking the button displays the text contained in the text box. Notice that the code in the event handler refers directly to username

<input type="button" value="Click Me" onclick="try{showMessage(); }catch(ex) {}">Copy the code

To prevent event handlers from firing before a function is defined, event handlers are typically wrapped in a try/catch block so that silent failure occurs in this case

Assign and remove
  • DOM2 event handler

Both assigning addEventListener() and removing removeEventListener() accept three parameters: the event name, the event handler, and a Boolean value (true means that the event handler is called in the capture phase, false means that the event handler is called in the bubble phase)

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

let btn = document.getElementById("myBtn"); btn.addEventListener("click", () => { console.log(this.id); // Press the button to print element ID}, false); btn.addEventListener("click", () => { console.log("Hello world!" ); // Then display the message Hello world! }, false);Copy the code

In particular, anonymous functions added using addEventListener() cannot be removed

// Let BTN = document.getelementById ("myBtn"); btn.addEventListener("click", () => { console.log(this.id); }, false); Btn.removeeventlistener ("click", function() {// No effect! console.log(this.id); }, false);Copy the code
// Let BTN = document.getelementById ("myBtn"); let handler = function() { console.log(this.id); }; btn.addEventListener("click", handler, false); // Other code btn.removeEventListener("click", handler, false); // It works!Copy the code
  • IE event handler

IE implements methods similar to DOM, namely attachEvent() and detachEvent(). Both methods take the same two parameters: the name of the event handler and the event handler function

Same as DOM2: Using DOM methods, anonymous functions added as event handlers cannot be removed. Unlike DOM2: When multiple event handlers are added to the same event, they are fired in reverse order of addition

Memory and performance

In JavaScript, the number of event handlers on a page is directly related to the overall performance of the page

  • Each function is an object and occupies memory space. The more objects there are, the worse performance there is
  • Specifying how many times an event handler needs to access the DOM causes a delay in the overall page interaction
Event delegation

When we have too many handlers on our page, the solution is to use event delegates. We can take advantage of the event bubbling feature and 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 id="sayHi">Say hi</li> </ul> <script> 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"); }); </script>Copy the code
<! 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; }});Copy the code

Adding just one event handler to document has the following advantages

  • You can add event handlers to the document at any time (without waiting for DOMContentLoaded or Load events)
  • Specifying only one event handler saves both DOM references and time
  • Reduce the memory required for the entire page and improve overall performance
Delete the event handler

The more connections browser code makes with event handlers in JS code, the worse the page performance will be

So we should also delete the different event handlers in a timely manner

<div id="myDiv"> <input type="button" value="Click Me" id="myBtn"> </div> <script type="text/javascript"> let btn = document.getElementById("myBtn"); Btn.onclick = function() {btn.onclick = null; // Delete event handler document.getelementById ("myDiv").innerhtml = "Processing..." ; }; </script>Copy the code

If you know an element will be deleted, it is a good idea to manually delete its event handler before deleting it