JavaScript > Events

Onunload in JavaScript

How to execute a function when element/object is unloaded in JavaScript?

In case we want to execute a function when a particular element/object is unloaded, we can follow this approach.

<body onunload="CallFunction()">
    Enter your name: <input type="text" name="txtName" id="txtName"  />
    <input type="button" id="btn" name="btn" value="Submit" />
    <a href="Add.htm">Go to Add page</a>

        function CallFunction() {
            alert("Navigating the page.");


In the above code snippet, we have specified onunload event in the body element that executes when the page is unloaded or user navigates from this page to another page. In this event we are executing “CallFunction()” function that shows alert like displayed below.


Note: In few browser this event doesn't executes.

 Views: 1147 | Post Order: 37

Write for us