Events

In JavaScript, events are actions or occurrences that happen in the browser, which your code can respond to. They enable interaction between users and your webpage.

What Are Events?

Events can be triggered by user actions like clicks, key presses, mouse movements, or by the browser itself (e.g., loading a page).

Common Event Types

  • click: User clicks an element
  • keydown: User presses a key
  • mouseover: Mouse pointer moves over an element
  • submit: Form submission
  • load: Page or image finishes loading

How to Listen to Events

You use addEventListener to attach a function (event handler) that runs when the event occurs.

📌 Deep Dive: Adding a Click Event Listener

JAVASCRIPT
const button = document.querySelector('button');

button.addEventListener('click', () => {
  alert('Button clicked!');
});
Output
A popup alert saying "Button clicked!" appears when the button is clicked.

Event Object

Event handlers receive an event object with details about the event, such as which key was pressed or mouse position.

📌 Deep Dive: Using the Event Object

JAVASCRIPT
document.addEventListener('keydown', (event) => {
  console.log('Key pressed:', event.key);
});
Output
Logs the name of the key pressed, e.g., "Key pressed: a"

Event Propagation: Capturing and Bubbling

Events propagate through the DOM in two phases:

  • Capturing phase: Event moves from the document root down to the target element.
  • Bubbling phase: Event bubbles up from the target element to the document root.

By default, listeners catch events during the bubbling phase, but you can listen during capturing by passing { capture: true } as an option.

Illustration of events
Illustration of events

💡 Event Propagation

Understanding event propagation helps you control which elements respond first and prevent unwanted side effects.

Removing Event Listeners

Use removeEventListener to detach an event handler. This requires a named function reference.

📌 Deep Dive: Removing an Event Listener

JAVASCRIPT
function onClick() {
  alert('Clicked!');
}

button.addEventListener('click', onClick);

// Later, to remove the listener:
button.removeEventListener('click', onClick);
Output
The alert will no longer appear after the listener is removed.

HTML Event Attributes vs. addEventListener

Comparing Event Binding Methods
MethodDescription
HTML attribute (e.g., onclick)Inline, mixes HTML & JS, limited flexibility
addEventListenerPreferred, allows multiple listeners, better separation

⚠️ Avoid Inline Event Handlers

Using inline event attributes like onclick is outdated and harder to maintain. Prefer addEventListener.

Summary

  • Events are how JavaScript responds to user and browser actions.
  • Use addEventListener to attach event handlers.
  • The event object provides useful information about the event.
  • Understand event propagation (capturing and bubbling).
  • Remove event listeners with removeEventListener when needed.