Skip to main content

DOM events

DOM events are signals generated by the browser to notify code of user interactions or changes in the document. Examples include clicks, key presses, and page loads. These events allow developers to create interactive and responsive web applications.

Basic Types of DOM Events

DOM events are categorized into several types, including:

  • Mouse Events: click, dblclick, mouseover, mouseout, mousemove, mousedown, mouseup
  • Keyboard Events: keydown, keypress, keyup
  • Form Events: submit, change, focus, blur
  • Window Events: load, resize, scroll, unload

Handling

To respond to DOM events, you use event handlers, which are functions that execute when a specific event occurs.

Adding Event Handlers

element.addEventListener(eventType, eventHandler, [options])

function handleClick() {
alert('Button clicked!');
}

button.addEventListener('click', handleClick);

Removing Event Handlers

element.addEventListener(eventType, eventHandler, [options])

element.removeEventListener('click', handleClick);

Event Propagation

Event propagation determines the order in which event handlers are executed.

Bubbling

The event starts from the target element and bubbles up to the ancestors. By default, all event handlers are executed on this phase.

Capturing

The event starts from the root and captures down to the target element. To execute the event handler on this phase, you need to add { capture: true } (or just true) as the third argument.

element.addEventListener('click', eventHandler, true);

Event Delegation

Event delegation leverages event propagation to manage events efficiently. Instead of attaching event handlers to multiple child elements, you attach a single handler to a common ancestor.

document.getElementById('parent').addEventListener('click', function (event) {
if (event.target && event.target.matches('childSelector')) {
// Handle the event
}
});

This technique is useful for dynamically added elements. Additionaly, it reduces memory usage and improves performance, especially in applications with many dynamic elements.

Preventing Event Handling

You can prevent default behavior and stop event propagation using some methods of Event object

  • event.preventDefault() Stops the default action associated with the event.
  • event.stopPropagation() Prevents the event from bubbling up or capturing down the DOM hierarchy.
  • event.stopImmediatePropagation() Prevents other listeners of the same event from being called.