The
unload()
method in jQuery is used to perform unload event when the user try navigates away from current webpage.The event can be triggered when user changes the dynamic state of the page for example user clicked on link to leave the page, a new URL is typed in the address bar etc. the unload method should only be use on window object. it specifies what will happen when a unload event occurs.
Syntax:
$(selector).unload(function)
Parameters
This method accepts only one and required parameter described below:
- Function:It is an required parameter which is used to specify the function to run when the unload event is triggered.
Example-1:
This example describes the triggering of unload event when you click on link.
<html>
<head>
<title>
jQuery unload() Method
title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
script>
head>
<body style="text-align:center;">
<br/>
<br/>
<br/>
<h1 style="color:green;">
GeeksForGeeks
h1>
<p>When you click
<a href="https://www.geeksforgeeks.org/">
Go to geeksa>, or close the window,
an alert box will be triggered.p>
<script>
$(document).ready(function() {
$(window).unload(function() {
alert("you are leaving from page");
});
});
script>
body>
html>
Output:
- Before click anywhere:

- After clicking on link or try to navigating away from the page

Example-2:
This example describes the triggering of unload event when you click on link.
<html>
<head>
<title>
jQuery unload() Method
title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
script>
<style>
h1 {
border: 1px solid black;
height: 100px;
padding-top: 35px;
background: green;
color: white;
}
style>
head>
<body style="text-align:center;">
<h1>GeeksForGeeksh1>
<script>
$(document).ready(function() {
$(window).unload(function() {
alert("you are leaving from page");
});
});
script>
<p>When you click <a href=
"https://www.geeksforgeeks.org/community/">GeeksForGeeksa>,
or close the window, an alert box will be triggered.p>
body>
html>
Output:
- Before click anywhere:

- After clicking on link or try to navigating away from the page

Note:
- The working of unload event depeandent on browsers.
- The unload() method was removed in version 3.0.
- The unload() method was deprecated in jQuery version 1.8.