tags:

views:

164

answers:

2

What is the JavaScript code/event(s) that is used by sites like stackoverflow and Gmail to test for the user exiting the page once they have begun editing and try to navigate away?

"Are you sure you want to navigate away from this page?"
+3  A: 

onbeforeunload event. Mozilla provides useful example code. you just want to have a function that:

  1. Returns a string
  2. Sets e.returnValue to that string, where e is the argument or window.event.

The string will be used as your custom message.

Matthew Flaschen
+5  A: 

The event used is called onbeforeunload.

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
</head>
<body>
    <input id="foo"></input>

    <script type="text/javascript">
        function unloadMessage() {
            return "Are you sure you want to leave?";
        }

        function setConfirmUnload(enabled) {
            window.onbeforeunload = enabled ? unloadMessage : null;
        }

        $(document).ready(function() {
            $("#foo").keypress(function() {
                setConfirmUnload(true);
            });
        });
    </script>
</body>
</html>
William Brendel
Remember `window.onbeforeunload` doesn't work in Opera, users will just navigate away, without warning.
Marcel Korpel
Are you sure it's $("#foo").change?It looks like change doesn't take effect until the field has lost the focus.
cf_PhillipSenn
You're right, it makes more sense to handle `keypress` instead of `change`. I updated my answer.
William Brendel
You may want to remove the keypress event listener after it has been triggered the first time. As is, setConfirmUnload is getting called for every keypress.
Matthew Flaschen