The browser unload event fires on window when the user leaves the page. In jQuery, bind it with .on("unload") (since 1.7) and simulate it with .trigger("unload").
Syntax
Start with these common calls. Keep them short and readable.
jQuery
// Bind on window (required pattern)
$(window).on("unload", function () {
// cleanup — keep it fast and simple
});
// Demo / tests only
$(window).trigger("unload");
// Removed shorthand (jQuery 3.0+)
// $(window).unload(fn);
Call
What it does
Unload
Learn the jQuery unload event: bind with $(window).on(\
Load jQuery before your script (CDN or local file), then wrap DOM work in $(function () { ... }) when needed.
Parameters
Parameter
Description
Step 1
Select $(window) — not body or a random element.
Step 2
Bind with .on("unload", handler).
Step 3
Do only fast sync cleanup (flags, storage writes). Avoid UI dialogs.
Return Value
Return Value
Description
jQuery object
Most setters and traversing helpers return the jQuery collection so you can chain more methods.
jQuery Examples
Example 1 — Bind and Simulate Unload
Official pattern: bind on window, then trigger for a safe demo.
jQuery
$(window).on("unload", function () {
$("#log").text("Handler for unload called.");
});
$("button").on("click", function () {
$(window).trigger("unload");
});
The unload event fires on the window when the user navigates away — link click, new URL, back/forward, tab close, or reload. Bind with $(window).on("unload", handler) since jQuery 1.7. Simulate with $(window).trigger("unload").
Official jQuery docs say unload handlers should be bound to the window object: $(window).on("unload", fn). That is the correct page-exit pattern.
unload runs while the page is leaving — mainly for cleanup. beforeunload fires earlier and can show a leave confirmation when the browser allows it. Use beforeunload only for unsaved-change warnings.
No. You cannot cancel unload with event.preventDefault(). For confirmations, use beforeunload and follow current browser prompt rules.
Same browser event. .unload(handler) was the shorthand removed in jQuery 3.0. .on("unload", handler) is the supported API. See the .unload() tutorial for migration.
Prefer pagehide or visibilitychange for reliable session-end logic. unload is unreliable on some mobile browsers, can break the back/forward cache, and is often discouraged. Use it mainly for legacy code or official-doc demos.