DOM Events
Events are actions or occurrences that happen in the browser, which you can respond to with JavaScript. Understanding events is crucial for creating interactive web applications.Adding Event Listeners
In order to add an event listener to an element, you can use theEventTarget.addEventListener() method. Yet, in some cases, adding a listener for every single element can be a bit of a performance hit.
Basic Event Listener
Event Delegation
In these cases, you can use event delegation to add a single event listener to a parent element and then check if the event target matches the target you’re looking for.Removing Event Listeners
Removing an event listener from an element is as easy as adding one. You can use theEventTarget.removeEventListener() method to remove an event listener from an element.
You must pass the same function reference to
removeEventListener that you passed to addEventListener. Arrow functions and anonymous functions won’t work for removal.Common Events
Mouse Events
Keyboard Events
Form Events
Window Events
Triggering Custom Events
JavaScript’sEventTarget.dispatchEvent() method allows you to trigger an event programmatically. This method accepts an Event object as its only argument, which can be created using the CustomEvent constructor.
Basic Custom Event
CustomEvent constructor allows you to pass custom data to the event listener through the detail property.
Custom Event with Options
Event Object Properties
Common Properties
Mouse Event Properties
Keyboard Event Properties
Event Methods
preventDefault()
Prevents the default action of the event:stopPropagation()
Stops the event from bubbling up the DOM tree:stopImmediatePropagation()
Stops event bubbling and prevents other listeners on the same element:Event Options
Capture Phase
Once
Passive
Practical Examples
Debounced Scroll Handler
Click Outside to Close
Keyboard Shortcuts
Best Practices
Use event delegation for dynamic content
Use event delegation for dynamic content
When elements are added/removed dynamically, event delegation ensures events work without re-attaching listeners.
Remove event listeners when done
Remove event listeners when done
Always remove event listeners when elements are destroyed or components unmount to prevent memory leaks.
Use passive listeners for scroll/touch
Use passive listeners for scroll/touch
Mark scroll and touch event listeners as passive to improve performance, unless you need preventDefault().
Don't use inline event handlers
Don't use inline event handlers
Avoid
onclick="..." in HTML. Use addEventListener in JavaScript for better separation of concerns.Throttle/debounce expensive handlers
Throttle/debounce expensive handlers
For events that fire frequently (scroll, resize, mousemove), use throttling or debouncing to limit execution.