Open In App

jQuery | unload() Method

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:

Example-1: This example describes the triggering of unload event when you click on link.




<!DOCTYPE html>
<html>
  
<head>
    <title>
        jQuery unload() Method
    </title>
  
    <script src=
    </script>
</head>
  
<body style="text-align:center;">
    <br/>
    <br/>
    <br/>
    <h1 style="color:green;">   
        GeeksForGeeks   
    </h1>
  
    <p>When you click
      <a href="https://ide.geeksforgeeks.org">
        Go to geeks</a>, or close the window,
      an alert box will be triggered.</p>
  
    <!-- Script to illustrates unload() method -->
    <script>
        $(document).ready(function() {
            $(window).unload(function() {
                alert("you are leaving from page");
            });
        });
    </script>
</body>
  
</html>

Output:



Example-2: This example describes the triggering of unload event when you click on link.




<!DOCTYPE html>
<html>
  
<head>
    <title>
        jQuery unload() Method
    </title>
  
    <script src=
    </script>
  
    <style>
        h1 {
            border: 1px solid black;
            height: 100px;
            padding-top: 35px;
            background: green;
            color: white;
        }
    </style>
</head>
  
<body style="text-align:center;">
  
    <h1>GeeksForGeeks</h1>
  
    <!-- Script to illustrates unbind() method -->
    <script>
        $(document).ready(function() {
            $(window).unload(function() {
                alert("you are leaving from page");
            });
        });
    </script>
    <p>When you click <a href=
    "https://ide.geeksforgeeks.org">GeeksForGeeks</a>,
   or close the window, an alert box will be triggered.</p>
  
</body>
  
</html>

Output:

Note:


Article Tags :