Fully understand the differences between addEventListener and on

  • 2021-07-02 23:35:31
  • OfStack

Why do you need addEventListener?

Let's look at a clip first:

html code

< div id="box" > Dream Chaser < /div >

Code with on


window.onload = function(){
  var box = document.getElementById("box");
  box.onclick = function(){
    console.log(" I am box1");
  }
  box.onclick = function(){
    box.style.fontSize = "18px";
    console.log(" I am box2");
  }
}
 Run result: "I am box2 " 

See, the second onclick covers the first onclick. Although we can accomplish the desired results with on in most cases, sometimes we need to perform multiple identical events. Obviously, if we can't accomplish what we want with on, don't guess, you must know, right! addEventListener can bind to the same event multiple times without overwriting one event.

Code with addEventListener


window.onload = function(){
  var box = document.getElementById("box");
  box.addEventListener("click",function(){
    console.log(" I am box1");
  })
  box.addEventListener("click",function(){
    console.log(" I am box2");
  })
}
 Run result: I am box1
 I am box2

The first parameter of the addEventListenert method fills in the event name, Note that on does not need to be written, the second parameter can be a function, the third parameter refers to the event handler in the bubble stage or capture stage, if true represents capture stage processing, if false represents bubble stage processing, the third parameter can be omitted, most cases do not need to use the third parameter, do not write the third parameter default false

Use of the third parameter

Sometimes the situation is like this

< body >
   < div id="box" >
     < div id="child" > < /div >
   < /div >
< /body >

If I add an click event to box, if I click box directly, there is no problem, but if I click child element, how does it perform? (Execution sequence)


box.addEventListener("click",function(){
  console.log("box");
})

child.addEventListener("click",function(){
  console.log("child");
})
 Results of implementation: 
          child
          box

That is, by default, events are executed in the order in which event bubbles are executed.

If the third parameter writes true, it follows the order in which the event capture is executed.


box.addEventListener("click",function(){
  console.log("box");
},true)

child.addEventListener("click",function(){
  console.log("child");
})
 Results of implementation: 
          box
          child

Event bubbling execution process:

Start with the most specific element (the one you click on) and start bubbling up. Take our case above and its order is: child- > box

Event capture execution process:

Start with the least specific element (the outermost box) and bubble inside. Take our case above and its order is: box- > child


Related articles: