The unload event fires on window when the user leaves the page. jQuery binds it with .on("unload", handler) and triggers it with .trigger("unload"). This tutorial covers official API patterns, cleanup use cases, comparisons with beforeunload and pagehide, the removed .unload() shorthand, and five interactive try-it examples.
01
window
Bind here
02
.on()
Bind
03
.trigger()
Fire
04
Cleanup
On exit
05
pagehide
Modern
06
Since 1.7
.on API
Fundamentals
Introduction
When a user clicks a link, types a new URL, presses back or forward, closes the tab, or reloads the page, the browser begins unloading the current document. jQuery exposes this lifecycle moment as the unload event on window.
Scripts historically used unload handlers for last-chance cleanup — flushing analytics, saving draft state, or tearing down timers. Bind with $(window).on("unload", handler) since jQuery 1.7, optionally pass eventData, and remove handlers with .off("unload", handler).
Browser vendors now discourage relying on unload because it is unreliable on mobile and harms back/forward cache performance. For new code, consider pagehide or visibilitychange. This page documents the official jQuery unload event API for learning and legacy maintenance. For the removed .unload() shorthand, see the .unload() tutorial.
Concept
Understanding the unload Event
The unload event is sent to the window element when navigation away from the page begins. It can fire on link navigation, address bar changes, history traversal, tab close, and page reload (reload triggers unload before the new load). Exact timing varies slightly between browsers — always test supported targets.
Handlers exist so scripts can perform cleanup. Most browsers ignore alert(), confirm(), and prompt() inside unload handlers. A returned string may appear in a confirmation dialog on some browsers, but this is inconsistent — use beforeunload for leave warnings. You cannot cancel navigation with event.preventDefault() on unload.
💡
Beginner Tip
Always bind to window: $(window).on("unload", fn). In try-it demos, simulate the event with $(window).trigger("unload") so you can test handlers without leaving the page.
Foundation
📝 Syntax
The modern jQuery API for the unload event has two main forms:
eventData — optional object available as event.data in the handler.
handler — function( event ) { ... } run when the page unloads.
Bind on $(window) per the official jQuery documentation.
2. Trigger the event — .trigger("unload") (since 1.0)
jQuery
.trigger( "unload" )
Runs bound unload handlers without a real browser navigation.
Useful for unit tests and interactive demos.
3. Unbind — .off("unload" [, handler])
jQuery
$( window ).off( "unload" ); // remove all unload handlers
$( window ).off( "unload", cleanup ); // remove specific handler
Official jQuery API examples
jQuery
$( window ).on( "unload", function() {
return "Handler for `unload` called.";
} );
// To display a message when the page is unloaded:
$( window ).on( "unload", function() {
return "Bye now!";
} );
Return value
.on() and .trigger() return the jQuery object for chaining.
Inside the handler, this refers to the window DOM object.
Cheat Sheet
⚡ Quick Reference
Goal
Code
Bind unload handler
$(window).on("unload", fn)
Bind with eventData
$(window).on("unload", { id: 1 }, fn)
Trigger handlers (demo/test)
$(window).trigger("unload")
Remove all unload handlers
$(window).off("unload")
Run cleanup once
$(window).one("unload", fn)
Leave confirmation
$(window).on("beforeunload", fn)
Modern page exit
$(window).on("pagehide", fn)
Compare
📋 unload vs beforeunload vs pagehide vs .unload()
Four page-lifecycle APIs — know which to use for cleanup, confirmations, and legacy code.
unload event
.on("unload")
Page is unloading — cleanup scripts; bind on window; cannot cancel navigation
beforeunload
confirm leave
Earlier in teardown — optional leave dialog for unsaved changes; strict browser rules
pagehide
recommended
Modern replacement for session-end logic — bfcache-friendly, more reliable on mobile
.unload() method
removed 3.0
Legacy shorthand for the same event — migrate to .on("unload") in jQuery 3+
Hands-On
Examples Gallery
Examples 1–3 follow the official jQuery API documentation. Examples 4–5 extend the pattern with session cleanup and a pagehide alternative. Use the Try-it links to run each snippet in the browser.
📚 Official API Demos
Binding and triggering from api.jquery.com/unload/.
Example 1 — Official Demo: Handler for unload Called
Bind on window and return a string from the handler — official jQuery API pattern.
Handler bound on window
On real navigation: unload fires during page exit
Try-it: trigger("unload") runs handler and logs message
Return value may show in dialog on some browsers — not guaranteed
How It Works
The handler runs as the document unloads. Returning a string historically influenced confirmation UI on some browsers, but behavior is inconsistent — do not rely on it for user prompts.
Example 2 — Official Demo: Display “Bye now!” on Unload
Second official example from the jQuery API — farewell message on page exit.
Handler returns "Bye now!" string
Browsers may ignore alert/confirm/prompt in unload handlers
Use beforeunload for intentional leave dialogs
How It Works
This mirrors the jQuery documentation example for displaying a message when the page unloads. Modern browsers restrict modal dialogs during unload — treat return strings as legacy behavior.
Example 3 — Trigger unload Programmatically
Fire bound handlers with .trigger("unload") — official trigger API since jQuery 1.0.
event.data.app === "editor"
sessionStorage key editor:lastExit set to timestamp
Keep unload handlers fast — long sync work may be killed by browser
How It Works
Passing eventData as the second argument to .on() avoids closure variables. Keep work minimal — browsers may terminate the page before slow handlers finish.
Example 5 — Prefer pagehide for New Code
Modern alternative when you need reliable page-lifecycle handling.
jQuery
// Recommended for new projects instead of unload
$( window ).on( "pagehide", function( event ) {
if ( event.originalEvent && event.originalEvent.persisted ) {
console.log( "Page entering bfcache" );
} else {
console.log( "Page leaving — run cleanup" );
navigator.sendBeacon( "/analytics", "exit" );
}
} );
pagehide fires when tab hidden or page navigated away
event.originalEvent.persisted === true when bfcache stores page
sendBeacon works well for analytics flush on exit
How It Works
When rewriting legacy .on("unload") code, evaluate whether pagehide fits your analytics and cleanup needs better. It cooperates with the back/forward cache unlike classic unload handlers.
Applications
🚀 Common Use Cases
Analytics beacons — flush pending events when the user leaves (prefer sendBeacon with pagehide).
Draft persistence — write form state to sessionStorage on exit.
Timer teardown — clear intervals tied to the page lifecycle.
Legacy maintenance — read existing .on("unload") handlers during jQuery upgrades.
Testing — use .trigger("unload") to verify cleanup logic in isolation.
Migration — replace removed .unload(fn) with .on("unload", fn).
🧠 How the unload Event Flows
1
User navigates away
Link click, URL change, back/forward, reload, or tab close starts document teardown.
Navigate
2
Browser fires unload
Event targets window — timing varies slightly by browser and navigation type.
Event
3
jQuery runs handlers
Handlers bound with .on("unload") execute — keep work short and synchronous.
Handler
4
🚫
Page unloads
Document destroyed — cannot cancel with preventDefault(); use beforeunload for warnings.
Important
📝 Notes
Bind handlers on $(window) — official jQuery requirement.
.on("unload") available since jQuery 1.7; .trigger("unload") since 1.0.
Cannot cancel navigation with event.preventDefault() on unload.
Most browsers ignore alert/confirm/prompt inside unload handlers.
Reload triggers unload before the new page load begins.
Mobile browsers may not fire unload reliably — test on real devices.
Legacy shorthand: .unload() removed in jQuery 3.0 — see dedicated tutorial.
Compatibility
Browser Support
The unload event exists in all major browsers but is discouraged for new code. Firing is inconsistent on mobile and when using back/forward cache. jQuery .on('unload') works wherever jQuery and the native event are supported. For production lifecycle handling, prefer pagehide and visibilitychange in evergreen browsers.
✓ Discouraged API
jQuery unload event
Bind with .on('unload') on window in jQuery 1.7+. Reliable enough for legacy maintenance; prefer pagehide for new session-end logic across modern browsers.
VariableNative event reliability
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
unload eventLegacy
Bottom line: Use for reading legacy code and official jQuery patterns — prefer pagehide when building new page-lifecycle features.
Wrap Up
Conclusion
The jQuery unload event fires on window when the user leaves the page. Bind with .on("unload", handler), trigger with .trigger("unload"), and unbind with .off("unload") — exactly as the official jQuery API documents.
For legacy shorthand removed in jQuery 3.0, see the .unload() tutorial. For new projects, evaluate pagehide before depending on unload in production.
Use .trigger("unload") to test handlers without navigating
Keep handlers fast — use sendBeacon for analytics
Prefer pagehide for new page-exit logic
Use beforeunload only for unsaved-change warnings
❌ Don’t
Expect reliable unload firing on all mobile browsers
Call alert() inside unload handlers
Try to cancel navigation with preventDefault()
Confuse unload with Ajax .load() or removed .unload() without reading docs
Run long async operations that may not complete before teardown
Summary
Key Takeaways
Knowledge Unlocked
Six things to remember about the unload event
Page-exit lifecycle on window — bind with .on(), not the removed shorthand.
6
Core concepts
win01
window
Bind here
Target
.on02
Bind
1.7+
API
!03
No cancel
Exit
Limit
→04
trigger
Test
Demo
ph05
pagehide
Modern
Better
.u()06
Shorthand
Removed
Legacy
❓ Frequently Asked Questions
The unload event fires on the window when the user navigates away from the page — link clicks, address bar navigation, back/forward buttons, tab close, or reload. Bind with $(window).on('unload', handler) since jQuery 1.7. Trigger programmatically with $(window).trigger('unload').
The official jQuery API states that unload handlers should be bound to the window object. $(window).on('unload', fn) is the correct pattern. Binding on body or other elements is not the standard approach for page-exit cleanup.
unload runs when the page is being unloaded — mainly for cleanup. beforeunload fires earlier and can show a leave confirmation if the handler returns a string (with browser restrictions). Use beforeunload only for unsaved-changes warnings, not general teardown.
No. You cannot cancel the unload event with event.preventDefault(). Once navigation starts, the page is leaving. For confirmation dialogs, use beforeunload instead and follow current browser rules for user-initiated prompts.
They target the same browser event. .unload(handler) was the legacy shorthand removed in jQuery 3.0. .on('unload', handler) is the modern supported API. See the .unload() tutorial for migration from old shorthand code.
Prefer pagehide or visibilitychange for reliable session-end logic — unload is unreliable on mobile, breaks back/forward cache, and is discouraged by browser vendors. Use unload or .on('unload') mainly when maintaining legacy code or mirroring official jQuery documentation.
Did you know?
jQuery documents the unload event and the removed .unload() method on separate API pages — same browser event, different jQuery APIs. The event page describes .on("unload") and .trigger("unload"); the shorthand page described .unload(handler) removed in 3.0. When auditing code, search for both patterns plus native window.onunload.