Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

The DOMContentLoaded, hashchange, mouseover, and focusin events

Choose the right listener target for DOM readiness, URL fragment changes, pointer entry, and focus. Use bubbling to handle descendant events from a shared container.

Version: Current web platform; runtime support varies

Syntax

document.addEventListener("DOMContentLoaded", onReady, { once: true });
window.addEventListener("hashchange", onHashChange);
container.addEventListener("mouseover", onMouseOver);
container.addEventListener("focusin", onFocusIn);

The DOMContentLoaded/hashchange/mouseover/focusin events tell you about four different things: document readiness, fragment navigation, pointer movement, and focus. They are Web Platform APIs. In the version field, ECMAScript 2024 refers only to the JavaScript language and does not specify support for these events. Check your target browsers for support; a JavaScript runtime alone does not guarantee a DOM.

Listen for DOMContentLoaded on document. The browser fires this non-cancelable Event after HTML parsing and after running classic defer scripts and non-async module scripts. It does not wait for images or async scripts; stylesheets can delay it indirectly by blocking a script. If setup only needs the parsed DOM, register with { once: true } when document.readyState === "loading"; otherwise run setup immediately. The "interactive" state does not prove the event has already fired.

Listen for hashchange on window when navigation changes the URL fragment within the same document, for example by assigning to location.hash. The HashChangeEvent carries full URLs in oldURL and newURL. Calling history.pushState() or history.replaceState() does not itself fire hashchange, even if the fragment changes.

mouseover is a MouseEvent fired at the element the pointer enters. It bubbles, so moving between descendants can also trigger a container's listener. relatedTarget is the element the pointer left, or null if there is no secondary target. To detect only entry from outside a container, listen directly for mouseenter, which does not bubble.

focusin is a non-cancelable FocusEvent fired when an element gains focus, for example when you press Tab. Unlike focus, focusin bubbles. When delegating focusin or mouseover in an ordinary DOM tree, read event.target for the affected element and event.currentTarget for the container whose listener is running.

Examples

(() => {
  const { document, window, HashChangeEvent, MouseEvent, FocusEvent } =
    typeof globalThis.document === "undefined" ? createNodeDemo() : globalThis;

  const container = document.createElement("div");
  const button = document.createElement("button");
  container.append(button);

  document.addEventListener("DOMContentLoaded", (event) => {
    console.log(`${event.type}: document=${event.target === document}`);
  }, { once: true });

  window.addEventListener("hashchange", (event) => {
    console.log(`${event.type}: ${new URL(event.oldURL).hash} -> ${new URL(event.newURL).hash}`);
  }, { once: true });

  for (const type of ["mouseover", "focusin"]) {
    container.addEventListener(type, (event) => {
      console.log(`${event.type}: button=${event.target === button}, container=${event.currentTarget === container}`);
    });
  }

  document.dispatchEvent(new Event("DOMContentLoaded", { bubbles: true }));
  window.dispatchEvent(new HashChangeEvent("hashchange", {
    oldURL: "https://example.com/#before",
    newURL: "https://example.com/#after",
  }));
  button.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
  button.dispatchEvent(new FocusEvent("focusin", { bubbles: true }));

  // Node.js fallback: model only the detached tree and event data used here.
  function createNodeDemo() {
    class DemoElement extends EventTarget {
      parentNode = null;

      append(child) {
        child.parentNode = this;
      }

      dispatchEvent(event) {
        let current = this;
        Object.defineProperties(event, {
          target: { configurable: true, value: this },
          currentTarget: { configurable: true, get: () => current },
        });

        try {
          for (; current; current = current.parentNode) {
            EventTarget.prototype.dispatchEvent.call(current, event);
            if (!event.bubbles || event.cancelBubble) break;
          }
        } finally {
          current = null;
        }
        return !event.defaultPrevented;
      }
    }

    class DemoHashChangeEvent extends Event {
      constructor(type, { oldURL, newURL }) {
        super(type);
        this.oldURL = oldURL;
        this.newURL = newURL;
      }
    }

    return {
      document: Object.assign(new EventTarget(), {
        createElement: () => new DemoElement(),
      }),
      window: new EventTarget(),
      HashChangeEvent: DemoHashChangeEvent,
      MouseEvent: Event,
      FocusEvent: Event,
    };
  }
})();

Result

DOMContentLoaded: document=true
hashchange: #before -> #after
mouseover: button=true, container=true
focusin: button=true, container=true

Run this in the browser console on `about:blank`, or save it as `main.js` and run `node main.js`. The browser uses its native DOM; the Node.js path uses a small model of the tree and events, not a DOM. `dispatchEvent()` fires synthetic events synchronously: it does not reload the document, change the URL, move the pointer, or move focus. The last two lines show bubbling from the button to a container that is not attached to the document.

Related lessons

  • JavaScript · Lesson 38 · Advanced · Version: 4

Sources