preface

The addEventListener method is widely used as a way to register events. Let’s take a look at this method and the hidden knowledge.

grammar

target.addEventListener(type, listener [, options]);
target.addEventListener(type, listener [, useCapture]);
target.addEventListener(type, listener [, useCapture, wantsUntrusted  ]); // Gecko/Mozilla only
Copy the code

According to the API in MDN, we can determine that addEventListener takes three parameters.

  • Type (i.e. event type, common ones like click, DomContentLoaded, error, etc.)

  • Listener A listener can be a function or an object with a handleEvent method

  • options

    • Capture (specifies whether the event behavior is to capture the event, default is false, i.e., bubble)
    • Once (Specifies whether the event is executed only once. The default value is false. When true, the event is automatically removed after being executed only once.)
    • Passive defaults to false, when specified as true, if the event itself has preventDefault, the user agent will do nothing and instead generate a console warning. We’ll talk more about that later

Common usage

<div class="btn"></div>
Copy the code
var btn = document.getElementById('btn')
btn.addEventListener('click'.function () {
  console.log('button is click');
})
Copy the code

Handler’s this points to

element.addEventListener('click'.function (e) {
  console.log(this.className)           // logs the className of my_element
  console.log(e.currentTarget === this) // logs `true`
})
Copy the code

Increase the rolling experience parameter passive

If the third option is set to true, the Scroll experience will be improved. According to the standard, the default value of passive is false. The latest Chrome and Firefox have set passive to true by default to improve scroll experience. Since browsers below Internet Explorer 9 do not support options, you need to hack through passive.

/* Feature detection */
let passiveIfSupported = false;

try {
  window.addEventListener("test".null.Object.defineProperty(
      {}, 
      "passive", 
      {
        get: function() { passiveIfSupported = { passive: false}; }})); }catch(err) {}

window.addEventListener('scroll'.function(event) {
  /* do something */
  // can't use event.preventDefault();
}, passiveIfSupported );
Copy the code