Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

DOMContentLoaded, pointerover, focusin, pagehide, and pageshow events

Choose the right event for DOM readiness, delegated pointer and focus handling, or navigation and restoration from the back/forward cache.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

document.addEventListener("DOMContentLoaded", onReady, { once: true });
container.addEventListener("pointerover", onPointerOver);
container.addEventListener("focusin", onFocusIn);
window.addEventListener("pagehide", onPageHide);
window.addEventListener("pageshow", onPageShow);

The DOMContentLoaded/pointerover/focusin/pagehide/pageshow events are web-platform APIs, not ECMAScript 2024 features; support depends on the runtime. Register listeners with addEventListener() and match the event names exactly, including case.

DOMContentLoaded is a non-cancelable Event fired at document after HTML parsing finishes, deferred classic scripts have run, and evaluation has started for non-async module scripts scheduled for the end of parsing. A module can still be suspended at a top-level await when the event fires. It does not wait for images, subframes, or async scripts. If code may start late and only needs the DOM to be built, listen once while document.readyState === "loading"; otherwise, run immediately. "interactive" alone does not mean the event has already fired.

pointerover (PointerEvent) fires when a pointer enters an element's hit-test area; on a touchscreen, this can happen on contact. Moving between descendants can produce more events. focusin (FocusEvent) fires when an element gains focus, for example via keyboard navigation or focus(), and cannot be canceled. Both events bubble, unlike pointerenter and focus. For delegation, event.target identifies the event target and event.currentTarget identifies the container with the listener.

On window, listen for pagehide when navigating away from a document and pageshow after the initial load and when a document is restored. Both are PageTransitionEvents. On pagehide, persisted === true means the browser intends to keep the document in the back/forward cache (bfcache), not that restoration is guaranteed. On pageshow, true means it was restored from bfcache without another DOMContentLoaded; false means the document was newly loaded. On restoration, resume work without registering listeners that are already in place.

Switching tabs alone is not navigation, and pageshow does not prove that the user can see the page. Observe visibility with visibilitychange and document.visibilityState. Save important data as it changes: pagehide can be skipped, for example if a mobile browser is terminated.

Examples

(() => {
  const inBrowser = typeof document !== "undefined" && typeof window !== "undefined";

  // Node's EventTarget has no DOM tree. Model just the bubbling used here.
  class DemoNode extends EventTarget {
    #parent = null;

    constructor(localName) {
      super();
      this.localName = localName;
    }

    append(child) {
      child.#parent = this;
    }

    dispatchEvent(event) {
      // Keep the original target while EventTarget supplies currentTarget.
      Object.defineProperty(event, "target", { value: this, configurable: true });
      for (let node = this; node; node = node.#parent) {
        super.dispatchEvent.call(node, event);
        if (!event.bubbles || event.cancelBubble) break;
      }
      return !event.defaultPrevented;
    }
  }

  class DemoPageTransitionEvent extends Event {
    constructor(type, { persisted = false } = {}) {
      super(type);
      this.persisted = Boolean(persisted);
    }
  }

  const doc = inBrowser ? document.implementation.createHTMLDocument() : new DemoNode("#document");
  const page = inBrowser ? window : new EventTarget();
  const Pointer = inBrowser ? window.PointerEvent : Event;
  const Focus = inBrowser ? window.FocusEvent : Event;
  const PageTransition = inBrowser ? window.PageTransitionEvent : DemoPageTransitionEvent;
  const createElement = (name) => inBrowser ? doc.createElement(name) : new DemoNode(name);
  const container = createElement("div");
  const button = createElement("button");
  container.append(button);
  (inBrowser ? doc.body : doc).append(container);

  doc.addEventListener("DOMContentLoaded", (event) => {
    console.log(event.type);
  });
  for (const type of ["pointerover", "focusin"]) {
    container.addEventListener(type, (event) => {
      console.log(`${event.type}: ${event.target.localName} -> ${event.currentTarget.localName}`);
    });
  }
  for (const type of ["pagehide", "pageshow"]) {
    page.addEventListener(type, (event) => {
      console.log(`${event.type}: persisted=${event.persisted}`);
    }, { once: true });
  }

  doc.dispatchEvent(new Event("DOMContentLoaded", { bubbles: true }));
  button.dispatchEvent(new Pointer("pointerover", { bubbles: true }));
  button.dispatchEvent(new Focus("focusin", { bubbles: true }));
  page.dispatchEvent(new PageTransition("pagehide", { persisted: true }));
  page.dispatchEvent(new PageTransition("pageshow", { persisted: true }));
})();

Result

DOMContentLoaded
pointerover: button -> div
focusin: button -> div
pagehide: persisted=true
pageshow: persisted=true

The example dispatches synthetic events. It shows bubbling from `button` to `div` and an explicitly supplied `persisted` value; it does not move focus, navigate, or use bfcache. It uses native APIs in a browser and a minimal event tree in Node.js.

Related lessons

  • JavaScript · Lesson 39 · Advanced · Version: 4

Sources