Everybody knows this classic way of handling events. We use it everyday

element.addEventListener('click', handlerFunc)

Interesting fact is that actually we can pass as a second arugment an object. When event fires, the handleEvent method will be called

<script>
element.addEventListener('click', {
  handleEvent(event) {
    // do stuff with event
  }
})
<script>


A simple example of usage, click the button to see an output.

See the Pen Events #1 by Karol Świeca (@khazarr) on CodePen.



This approach gives us an oppurtunity to create an object (or even a ES6 class) which will store multiple handlers for events. I find it quite clear to use. Check out example

  class BtnHandler {
    handleEvent(event) {
      switch(event.type) {
        case 'mousedown':
          // do stuff on mouse down
          break;
        case 'mouseup':
        // do another stuff on mouse up
          break;
        case 'mouseenter':
        // do another stuff on mouseenter
          break;
        case 'mouseleave':
        // do another stuff on mouseleave
          break;
      }
    }
  }

  let handler = new BtnHandler();
  el.addEventListener('mousedown', handler);
  el.addEventListener('mouseup', handler);
  el.addEventListener('mouseenter', handler);
  el.addEventListener('mouseleave', handler);

See the Pen Events #2 by Karol Świeca (@khazarr) on CodePen.


Summary

  • options for addEventListener
// passing a reference to a function or an object which posses handleEvent method
el.addeventListner('eventName', functionReferenceOrObject)


// or creating an anonymous callack
el.addeventListner('eventName', event => {
  //do stuff with it
})

Karol Świeca

My thougths on JavaScript, AWS Cloud and other aspects of being Software Engineer