onWindow and onDocument

So far, we have discussed how to listen to events that originate at elements. There are events (for example, scroll and mousemove) that require that we listen to them on window or document. For this reason, Qwik allows for the onWindow and onDocument prefixes when listening for events.

const EventExample = component$(() => {
  const store = useStore({
    scroll: 0,
    mouse: { x: 0, y: 0 },
    clickCount: 0,
  });

  return (
    <button
      onWindowScroll$={(e) => (store.scroll = window.scrollY)}
      onDocumentMousemove$={(e) => {
        store.mouse.x = e.x;
        store.mouse.y = e.y;
      }}
      onClick$={() => store.count++}
    >
      scroll: {store.scroll}
      mouseMove: {store.mouse.x}, {store.mouse.y}
      click: {store.clickCount}
    </button>
  );
});

The purpose of the onWindow/onDocument is to register the event at a current DOM location of the component but have it receive events from the window/document. There are two advantages to it:

  1. The events can be registered declaratively in your JSX
  2. The events get automatically cleaned up when the component is destroyed. (No explicit bookkeeping and cleanup is needed.)