jQuery Unload Event

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Browser event

What You’ll Learn

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

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.

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.

📝 Syntax

The modern jQuery API for the unload event has two main forms:

1. Bind a handler — .on("unload" [, eventData ], handler) (since 1.7)

jQuery
.on( "unload" [, eventData ], handler )
  • eventData — optional object available as event.data in the handler.
  • handlerfunction( 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.

⚡ Quick Reference

GoalCode
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)

📋 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+

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.

jQuery
$( window ).on( "unload", function() {
  return "Handler for `unload` called.";
} );
Try It Yourself

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.

jQuery
$( window ).on( "unload", function() {
  return "Bye now!";
} );
Try It Yourself

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.

jQuery
$( window ).on( "unload", function() {
  $( "#log" ).text( "Handler for unload called." );
} );

$( "#other" ).on( "click", function() {
  $( window ).trigger( "unload" );
} );
Try It Yourself

How It Works

Same pattern as scroll and error event tutorials: a control button triggers the event on another target. Here the target is window itself.

📈 Practical Patterns

Session cleanup and modern lifecycle alternatives.

Example 4 — Session Cleanup on Unload

Save a timestamp to sessionStorage when the user leaves — typical cleanup use case.

jQuery
$( window ).on( "unload", { app: "editor" }, function( event ) {
  sessionStorage.setItem(
    event.data.app + ":lastExit",
    Date.now()
  );
} );
Try It Yourself

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" );
  }
} );
Try It Yourself

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.

🚀 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.

📝 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.

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.

Variable Native event reliability
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
unload event Legacy

Bottom line: Use for reading legacy code and official jQuery patterns — prefer pagehide when building new page-lifecycle features.

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.

💡 Best Practices

✅ Do

  • Bind on $(window).on("unload", fn)
  • 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

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
.on 02

Bind

1.7+

API
! 03

No cancel

Exit

Limit
04

trigger

Test

Demo
ph 05

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.

Next: jQuery .unload() Method

Legacy shorthand removed in jQuery 3.0 — migration and browser notes.

.unload() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful