This is the sixth day of my participation in the More text Challenge. For details, see more text Challenge

JavaScript uses an asynchronous event-driven programming model, where interaction with HTML is achieved through events.

When we execute a specific event, such as the click event on a button, when you press the button, it will trigger your given event handler (also called event handler, which executes some JS statements). But what about the triggering process? Let’s look at the propagation mechanism of today’s events through some questions.

You can test the results here at 👉 and read them below.

What is the flow of events?

An event stream is the order in which events are received on a web page. When you click on an element nested within a variety of other elements, after you click on the target element, it fires the click event on the target element first, firing up through the layers until it reaches the window object at the top, which is the default browser event bubble behavior (IE 9+). There are two ways to stream events:

  • From outside to inside (event capture)
  • From the inside out (event bubble)

Simple example: This structure is used for the following problems

<ul id="emoji">
  <li id="smile">😀</li>
  <li>😁</li>
  <li>😂</li>
  <li>🤣</li>
  <li>😃</li>
  <li>😄</li>
</ul>

<script>
  emoji.onclick = function (e) {
    console.log(e.target.innerHTML)
  }
</script>
Copy the code

Try using the above example and you’ll find that clicking on each

  • TAB will give you each emoji.
  • This results because it uses one of the most important principles of event bubbles: Event delegation, which I’ll cover later.

    Event flow in IE

    Here to introduce IE 6-8 event flow, IE 6-8 event flow and the standard DOM event flow has (unique) not (wind) the same, IE event flow only supports event bubble, does not support event capture.

    Prior to IE 9, it also did not support addEventListener, which means it cannot use its third argument to indicate whether it is a bubble or a capture, and it provides the non-standard attachEvent() method for event listeners.

    In this model, event objects use the event.srcElement attribute instead of event.target, but the effect is the same.

    emoji.attachEvent('onclick'.function (e) {
      var target = e.target || e.srcElement
      alert(target.innerHTML)
    })
    Copy the code

    What is an event bubble?

    Event bubbling is a type of event propagation in which events are first fired on the innermost target element and then in turn on the ancestors (parents) of the target element in the same nested hierarchy until they reach the outermost DOM element.

    emoji.onclick = function () {
      alert(11)
    }
    
    smile.onclick = function () {
      alert(22)}/ / 11
    / / 22
    Copy the code

    What is event capture?

    Event capture is also a form of event propagation, in which the event is first captured by the outermost element and then in turn triggers the descendants (children) of the target element in the same nested hierarchy until it reaches the innermost DOM element.

    To each DOM node, an event is propagated between two DOM nodes. The DOM event standard describes three stages of event propagation:

    • Capture phase: Events are passed down from the Window object to the target node.

    • Target Phase: The event reaches the target element.

    • Bubbling phase: Events start bubbling from the elements.

    During the capture phase, events are propagated from the ancestor element down to the target element. The bubble starts when the event reaches the target element.

    At the same time, the propagation model of these three stages causes an event to be triggered on multiple nodes.

    Since the browser starts with the event bubble by default, we can’t see event capture, so to test event capture we need to use the addEventListener method. AddEventListener is used to add the event handle and register the listener. Parameter 3 also specifies whether the event is triggered during the capture phase or during the bubble phase:

    • false(default) — Starts firing events during the bubbling phase;
    • true— Starts firing events during the capture phase.
    smile.addEventListener('click'.function(e) {
      console.log(e.target.innerHTML)
    })
    
    emoji.addEventListener('click'.function(e) {
      alert('Emoji List')},true)
    
    document.addEventListener('click'.function () {
      alert('document')})window.addEventListener('click'.function () {
      alert('window')})// When smile is clicked, output 'Emoji List' -> 😀 -> 'document' -> 'window'
    // Since the list is set to start the capture phase, it fires first, at 😀, and then upwards.
    Copy the code

    Event delegation

    An event delegate, also known as an event agent, is the process of adding events to someone else that would otherwise have been added to itself. Through the principle of bubble, the event is added to the parent level, triggering the execution effect.

    emoji.addEventListener('click'.function(e) {
      console.log(e.target.innerHTML)
    })
    Copy the code

    benefit

    • Saves memory usage and reduces event registration
    • When a new child object is added, it does not need to be event bound

    Prevent event propagation

    Use the event.stopPropagation() method to prevent further propagation of current events in the DOM during the capture and bubbling phases.

    function handler(e) { 
      e.stopPropagation()
    }
    Copy the code

    Cancel default events

    Use the event.preventdefault () method to cancel the browser default for the current event, for example:

    • Form element, which prevents it from being submitted
    • Used in the anchor element, which prevents it from navigating
    • Context menu, which prevents it from being shown or hidden
    function handler(e) { 
      e.preventDefault()
    }
    Copy the code

    You can also use event.defaultaim in the event object to see whether the event.preventdefault () method is used.

    It returns a Boolean value indicating whether event.preventDefault() has been called on a particular element.

    function handler(e) {
      e.preventDefault()
      console.log(e.defaultPrevented) // true or false
    }
    Copy the code

    What steps are involved in the return false usage

    The return false statement in the event handler performs the following steps:

    • First, it stops the default action or behavior of the browser.
    • It prevents events from propagating the DOM
    • Stops callback execution and returns immediately upon invocation.

    Understanding event propagation requires attention

    • The event itself propagates, not the methods bound to the event.
    • Not all events will spread, likefocus.blurThe event is not transmitted,mouseentermouseleaveEvents do not spread;
    • You should know which events have default behavior and prevent it if necessary.
    • If you’re usingon<event>Assigned to the handler, then you can usereturn falseTo prevent the default behavior.
    • The value returned by the event handler is usually ignored. The only exception is from useon<event>From the assigned handlerreturn false. In all other cases,returnValues are ignored. And, returntrueIt doesn’t make sense.
    • If you’re usingaddEventListener, you can usereturn false, but commonly used is to useeventIn the objecte.preventDefault()Method to prevent the default behavior.
    • return falseTo do withevent.stopPropagation()event.preventDefault()Similar jobs, but they’re not related.