CKTIS / JavaScript
wheel, pagehide, pageshow, and beforeunload events
Distinguish wheel input from scrolling, detect when a page resumes from the back/forward cache, and warn users before unsaved changes are lost.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
element.addEventListener("wheel", onWheel, { passive: true });
window.addEventListener("pagehide", onPageHide);
window.addEventListener("pageshow", onPageShow);
window.addEventListener("beforeunload", onBeforeUnload);
window.removeEventListener("beforeunload", onBeforeUnload);The wheel/pagehide/pageshow/beforeunload events are browser APIs, not part of ECMAScript 2024. Listen for wheel on an element and for pagehide, pageshow, and beforeunload on window. Behavior details vary by browser.
wheel (WheelEvent) reports a mouse-wheel or trackpad gesture, not actual scrolling: a gesture may zoom or move nothing, and a keyboard can scroll without it. deltaX and deltaY describe the gesture; deltaMode gives the unit: 0 for pixels, 1 for lines, 2 for pages. To detect actual movement, compare scrollLeft and scrollTop in a scroll listener. Use { passive: true } to observe. If you must block default scrolling or zooming, use { passive: false } and call preventDefault() only if event.cancelable is true. Some browsers let you cancel only the first event in a sequence.
pagehide and pageshow are PageTransitionEvents. When leaving a page, pagehide with persisted: true means the page may be kept in the back/forward cache (bfcache), not that a later restore is guaranteed. pageshow with persisted: true means the same page resumed from bfcache; on initial load, pageshow follows load and has persisted: false. Neither event tracks ordinary tab switches, and pageshow does not prove the page is visible. preventDefault() does not stop these transitions.
beforeunload (BeforeUnloadEvent) can fire before closing, reloading, or navigating away. Call preventDefault() to request a confirmation dialog; for legacy compatibility, also set event.returnValue to a nonempty string. Returning a nonempty string from the handler is a legacy mechanism for onbeforeunload, not addEventListener(). The dialog requires prior user interaction (sticky activation), is not guaranteed, and uses browser-controlled text.
Attach beforeunload only while edits are unsaved and remove it after saving or discarding them. Neither pagehide nor beforeunload is reliable, especially on mobile. Save as work progresses, and use visibilitychange on document when document.visibilityState === "hidden" as an additional cue to save, not as proof that the session ended.
Examples
(() => {
const element = typeof document === "undefined"
? new EventTarget()
: document.createElement("div");
const page = new EventTarget();
element.addEventListener("wheel", (event) => {
const unit = event.deltaMode;
if (event.cancelable) event.preventDefault();
console.log(`wheel: deltaY=${event.deltaY}, deltaMode=${unit}, canceled=${event.defaultPrevented}`);
}, { passive: false });
const logTransition = (event) => {
console.log(`${event.type}: persisted=${event.persisted}`);
};
page.addEventListener("pagehide", logTransition);
page.addEventListener("pageshow", logTransition);
page.addEventListener("beforeunload", (event) => event.preventDefault());
const wheel = typeof WheelEvent === "function"
? new WheelEvent("wheel", {
deltaY: 3, deltaMode: WheelEvent.DOM_DELTA_LINE, cancelable: true
})
: Object.assign(new Event("wheel", { cancelable: true }), {
deltaY: 3, deltaMode: 1 // Lines, as with WheelEvent.DOM_DELTA_LINE.
});
const transition = (type) => typeof PageTransitionEvent === "function"
? new PageTransitionEvent(type, { persisted: true })
: Object.assign(new Event(type), { persisted: true });
element.dispatchEvent(wheel);
page.dispatchEvent(transition("pagehide"));
page.dispatchEvent(transition("pageshow"));
const result = page.dispatchEvent(new Event("beforeunload", { cancelable: true }));
console.log(`beforeunload: dispatchEvent returned ${result}`);
})();Result
wheel: deltaY=3, deltaMode=1, canceled=true pagehide: persisted=true pageshow: persisted=true beforeunload: dispatchEvent returned false
Run in a browser console or in Node.js 24. In a browser, the synthetic `wheel` event goes to a detached element. In Node.js, an `EventTarget` replaces the element, and plain `Event` objects carry the wheel and transition fields. In both environments, a separate `EventTarget` stands in for `window`. `false` means the test event was canceled, not that navigation was blocked. The code does not scroll, restore a page from bfcache, or open a dialog.
Related lessons
- JavaScript · Lesson 36 · Advanced · Version: 4
Sources
- Element: wheel event
- WheelEvent: deltaMode property
- WheelEvent: WheelEvent() constructor
- Window: pagehide event
- Window: pageshow event
- HTML Standard: The PageTransitionEvent interface
- Window: beforeunload event
- HTML Standard: Preventing navigation
- Document: visibilitychange event
- EventTarget: dispatchEvent() method