J

JavaScript Handbook

Clean • Professional

Introduction to Events in JavaScript

2 minute

Introduction to Events

In JavaScript, events are actions or occurrences that happen in the browser or on the user interface, such as clicking a button, typing in a text field, or resizing the window. Events allow JavaScript to respond to user interactions, making web pages dynamic and interactive.

Event Types

Events can be broadly categorized based on their origin:

  • User Interface (UI) Events: load, resize, scroll
  • Mouse Events: click, dblclick, mouseover, mouseout, mousemove
  • Keyboard Events: keydown, keyup, keypress
  • Form Events: submit, change, input, focus, blur
  • Clipboard Events: copy, cut, paste
  • Drag & Drop Events: dragstart, dragover, drop
  • Custom Events: User-defined events to trigger specific logic

Event Handling

Event handling allows JavaScript to respond to events.

Methods to handle events:

  1. Inline HTML: <button onclick="doSomething()">Click</button>
  2. DOM Property: element.onclick = function() { ... }
  3. addEventListener (Preferred):
const btn = document.getElementById("myButton");
btn.addEventListener("click", () => {
  console.log("Button clicked!");
});

Event Object:

When an event occurs, an event object is passed to the handler containing information like:

  • event.type – type of event
  • event.target – element that triggered the event
  • event.preventDefault() – prevent default browser behavior
  • event.stopPropagation() – stop the event from bubbling

Event Propagation

Event propagation defines how events travel through the DOM. There are three phases:

  1. Capturing Phase: Event travels from the root down to the target element.
  2. Target Phase: Event reaches the target element.
  3. Bubbling Phase: Event bubbles up from the target back to the root.
element.addEventListener("click", handler, true); // true → capturing
element.addEventListener("click", handler, false); // false → bubbling (default)

Methods to control propagation:

  • event.stopPropagation() – stops further propagation
  • event.stopImmediatePropagation() – stops other listeners on the same element

Event Handling Patterns

Some common patterns for event handling:

  • Direct Event Binding: Attach handler to each element individually
  • Event Delegation: Attach a single handler to a parent element to manage events of its children
document.getElementById("parent").addEventListener("click", (event) => {
  if (event.target.tagName === "BUTTON") {
    console.log("Button inside parent clicked");
  }
});

One-time Event Listeners: Execute handler only once

element.addEventListener("click", handler, { once: true });

Prevent Default Behavior: For forms, links, or custom actions

form.addEventListener("submit", (e) => e.preventDefault());

 

Article 0 of 0