← Lesson
BitWithBite
JavaScript · Quick Reference

Lesson 11 — Events Cheat Sheet

JavaScript
In one line: The addEventListener method attaches a function to fire when a specific event occurs on an element. This is the modern, preferred way to handle events.

Key Ideas

1addEventListener Basics. The addEventListener method attaches a function to fire when a specific event occurs on an element. This is the modern, preferred way to handle events.
2The Event Object. Every event handler receives an event object (usually called e or event) containing useful information about what happened.
3Event Delegation. Instead of adding listeners to many elements, attach one listener to the parent and check e.target. This is more efficient and works for dynamically added elements.

Code Examples

// Syntax: element.addEventListener(event, handler, options) const btn = document.querySelector('#myBtn'); // Click events btn.addEventListener('click', () => console.log('Clicked!')); btn.addEventListener('dblclick', () => console.log('Double c...
// e.target — the element that was clicked document.addEventListener('click', e => { console.log(e.target); // element that was clicked console.log(e.target.tagName); // 'BUTTON', 'DIV', etc. console.log(e.target.id); // eleme...
// BAD — adding listener to each button (inefficient) document.querySelectorAll('.delete-btn').forEach(btn => { btn.addEventListener('click', handleDelete); }); // GOOD — one listener on the parent (event delegation) const list = document.getEle...