J

JavaScript Handbook

Clean • Professional

DOM Events in JavaScript

3 minute

DOM Events

In the HTML DOM, events are actions or occurrences that happen in the browser, often triggered by the user or the browser itself. JavaScript uses event handling to detect these actions and respond dynamically, making web pages interactive and responsive.

What is a DOM Event?

A DOM event is any activity that a webpage or its elements can detect, such as:

  • User actions: clicking a button, typing in a text box, hovering over an element.
  • Browser actions: page load, resizing, scrolling, or errors.
  • Form actions: submitting a form, changing input values.

Common Event Types

TypeExamplesDescription
Mouse Eventsclick, dblclick, mouseover, mouseout, mousemoveDetect mouse interactions with elements.
Keyboard Eventskeydown, keyupDetect keyboard input.
Form Eventssubmit, input, change, focus, blurTriggered by form or input actions.
Window/Document Eventsload, resize, scroll, unloadTriggered by browser or window actions.
Clipboard Eventscopy, cut, pasteDetect clipboard operations.

Event Handling in JavaScript

There are three ways to handle events in JavaScript:

1. Inline Event Handling

Directly in HTML using attributes.

<button onclick="alert('Button clicked!')">Click Me</button>

2. DOM Property

Assign a function to an element’s event property.

const button = document.getElementById("myButton");
button.onclick = function() {
  alert("Button clicked!");
};

3. addEventListener() (Recommended)

Attach multiple listeners to the same event without overriding others.

const button = document.getElementById("myButton");
button.addEventListener("click", (event) => {
  alert("Button clicked!");
});

Event Object

When an event occurs, an event object is automatically passed to the handler. It contains useful properties:

  • event.target — The element that triggered the event.
  • event.type — Type of event (click, input, etc.).
  • event.preventDefault() — Prevents the default browser behavior.
  • event.stopPropagation() — Stops the event from bubbling or capturing.

Example:

const link = document.querySelector("a");
link.addEventListener("click", (event) => {
  event.preventDefault(); // Stops page from navigating
  console.log("Link clicked:", event.target.href);
});

Event Propagation

Events can move through the DOM in two ways:

  1. Bubbling: Event starts at the target element and bubbles up to parent elements (default behavior).
  2. Capturing: Event starts at the topmost ancestor and propagates down to the target element.

Control Propagation:

element.addEventListener("click", handler, { capture: true }); // Capturing phase

Stop Bubbling:

element.addEventListener("click", (event) => {
  event.stopPropagation(); // Stops event from reaching parent
});

Examples of Event Handling

Mouse Events

const div = document.getElementById("box");
div.addEventListener("mouseover", () => {
  div.style.backgroundColor = "yellow";
});
div.addEventListener("mouseout", () => {
  div.style.backgroundColor = "white";
});

Keyboard Events

document.addEventListener("keydown", (event) => {
  console.log("Key pressed:", event.key);
});

Form Events

const form = document.getElementById("myForm");
form.addEventListener("submit", (event) => {
  event.preventDefault();
  console.log("Form submitted");
});

const input = form.elements["username"];
input.addEventListener("input", () => {
  console.log("Typing:", input.value);
});
input.addEventListener("change", () => {
  console.log("Final value:", input.value);
});

Focus Events

input.addEventListener("focus", () => {
  input.style.border = "2px solid blue";
});
input.addEventListener("blur", () => {
  input.style.border = "1px solid gray";
});

Clipboard Events

document.addEventListener("copy", () => console.log("Content copied!"));
document.addEventListener("paste", () => console.log("Content pasted!"));

Real-World Example — Interactive Form

<form id="myForm">
  <input type="text" name="username" placeholder="Username">
  <input type="email" name="email" placeholder="Email">
  <button type="submit">Submit</button>
</form>

<script>
  const form = document.getElementById("myForm");
  const username = form.elements["username"];
  const email = form.elements["email"];

  // Form submission
  form.addEventListener("submit", (e) => {
    e.preventDefault();
    console.log({ username: username.value, email: email.value });
    if (!username.value) {
      alert("Username required!");
      username.focus();
    }
  });

  // Real-time validation
  email.addEventListener("input", (e) => {
    e.target.style.border = e.target.value.includes("@")
      ? "2px solid green"
      : "2px solid red";
  });
</script>

 

Article 0 of 0