W3cubDocs

/jQuery

.unload()

.unload( handler )Returns: jQueryversion deprecated: 1.8, removed: 3.0

Description: Bind an event handler to the "unload" JavaScript event.

Note: This API has been removed in jQuery 3.0; please use .on( "unload", handler ) instead of .unload( handler ) and .trigger( "unload" ) instead of .unload().

This method is a shortcut for .on( "unload", handler ).

The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.

The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers and contrasted with the similar beforeunload event.

Any unload event handler should be bound to the window object:

$( window ).unload(function() {
  return "Handler for .unload() called.";
});

This event is available so that scripts can perform cleanup when the user leaves the page. Most browsers will ignore calls to alert(), confirm() and prompt() inside the event handler. The string you return may be used in a confirmation dialog, but not all browsers support this. It is not possible to cancel the unload event with .preventDefault().

Additional Notes:

  • As the .unload() method is just a shorthand for .on( "unload", handler ), detaching is possible using .off( "unload" ).

Example:

To display an alert when a page is unloaded:

$( window ).unload(function() {
  return "Bye now!";
});

© The jQuery Foundation and other contributors
Licensed under the MIT License.
https://api.jquery.com/unload