Anatomy of Event Listeners and Passive Listeners: Advanced Javascript

Vamsi Krishna Kodimela
Angular Simplified
Published in
2 min readFeb 19, 2024

--

Events and Listeners bring life to your web application. To start with Event listeners, best practices, and more, take a look at my previous article:

Anatomy of Event Listeners

The “addEventListener” method is the heart of the event listener. Let’s dig deep into it. Every listener will have 3 arguments:

  • Event Type: Event you want to listen to: click, scroll, keydown,…
  • Event Listener Function: A function that will be called when a specific event occurs.
  • Even Listener Options (options): An object containing options like capture, once and importantly, passive.

Supported Options:

  • capture (boolean): Controls the bubbling phase of event propagation.
  • once (boolean): Determines if the listener triggers only once for the specified event
  • passive (boolean): Improves scrolling performance on touch devices.
document.getElementById("myButton").addEventListener("click", function() {
console.log("Button clicked!");
});

Passive Event Listeners: Boosting Scrolling Performance

  • Passive event listeners are features introduced to introduce scrolling performance on touch devices.
  • Usually browsers block scrolling until the event listener finisher. It may cause laggy scrolling expereience.
  • Passive listeners solve this by signaling to the browser that the listener won’t interfere with scrolling.

By setting the passive option to true in the listener options:

document.getElementById("myElement").addEventListener("touchstart", function() {
// Do something without calling preventDefault
}, { passive: true });

Note

  • Passive listeners cannot call preventDefault, otherwise, a console warning will be thrown.
  • They are not supported for all events, only touch and wheel events.

Conclusion

Mastering event listeners and understanding passive listeners are crucial for writing performant and responsive web applications. By carefully choosing the right listener type and techniques, you can create smooth and user-friendly experiences.

--

--