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
| Category | Examples |
|---|---|
| Mouse | click, dblclick, mousemove, mouseover, mouseout, contextmenu |
| Keyboard | keydown, keyup, keypress |
| Input | input, change, focus, blur, submit |
| Document / window | load, scroll, resize, DOMContentLoaded |
| Other | transitionend, 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:
- Capturing - from
documentdown to the target element. - Target - the event itself on the relevant element.
- 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:
javascriptbtn.addEventListener('click', () => console.log('Once'), { once: true }); -
You can prevent the browser's default action:
javascriptform.addEventListener('submit', e => { e.preventDefault(); // cancels the form submission });
Summary
| Concept | What it is |
|---|---|
| Event | A notification about an action (click, input, load, and so on) |
| Handler | The function called when the event occurs |
| event.target | The 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.