Skip to main content

What is an event in the DOM?

An event in the DOM is a signal from the browser that tells you something happened: the user clicked, hovered the mouse, pressed a key, the page loaded, and so on.


Simple definition

An event is an object that describes an action (user-triggered or system) that occurred in the browser. You can respond to an event using an event listener (handler).


Event examples

CategoryExamples
Mouseclick, dblclick, mousemove, mouseover, mouseout, contextmenu
Keyboardkeydown, keyup, keypress
Inputinput, change, focus, blur, submit
Document / windowload, scroll, resize, DOMContentLoaded
Othertransitionend, animationstart, drag, drop, error

Example: handling a click

javascript
<button id="btn">Click me</button> <script> const btn = document.querySelector('#btn'); btn.addEventListener('click', () => { alert('Button clicked!'); }); </script>

Here:

  • "click" is the event type,
  • the function is the event handler (what to do on click).

How addEventListener works

javascript
element.addEventListener(eventType, handler, options);
  • eventType - the event name (for example, 'click');
  • handler - the function called when it fires;
  • options - (optional) flags such as { once: true } or { capture: true }.

The event object (event)

When an event fires, an object with details is passed to the handler:

javascript
btn.addEventListener('click', (event) => { console.log(event.type); // "click" console.log(event.target); // the element that was clicked });

Bubbling and capturing

Events in the DOM propagate through the tree:

  1. Capturing - from document down to the target element.
  2. Target - the event itself on the relevant element.
  3. Bubbling - back up.

This means one event can be "caught" by a parent element:

javascript
document.body.addEventListener('click', () => { console.log('Click on the page body!'); });

Removing a handler

To remove a listener:

javascript
function handleClick() { console.log('click!'); } btn.addEventListener('click', handleClick); btn.removeEventListener('click', handleClick);

Features

  • You can attach multiple handlers to one event.

  • You can limit it to firing once:

    javascript
    btn.addEventListener('click', () => console.log('Once'), { once: true });
  • You can prevent the browser's default action:

    javascript
    form.addEventListener('submit', e => { e.preventDefault(); // cancels the form submission });

Summary

ConceptWhat it is
EventA notification about an action (click, input, load, and so on)
HandlerThe function called when the event occurs
event.targetThe element on which the event occurred
addEventListener()The method to subscribe to an event
removeEventListener()The method to unsubscribe
e.preventDefault()Cancels the default behavior
e.stopPropagation()Stops the event from bubbling

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.