Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are you sure you want to navigate?

Tags:

javascript

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?"
like image 497
Phillip Senn Avatar asked Feb 25 '10 02:02

Phillip Senn


People also ask

What is navigating away?

vb. 1 to plan, direct, or plot the path or position of (a ship, an aircraft, etc.) 2 tr to travel over, through, or on (water, air, or land) in a boat, aircraft, etc. 3 Informal to direct (oneself, one's way, etc.) carefully or safely.

How do I use Windows Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.


2 Answers

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>
like image 75
William Brendel Avatar answered Sep 30 '22 10:09

William Brendel


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.

like image 36
Matthew Flaschen Avatar answered Sep 30 '22 11:09

Matthew Flaschen