Javascript onload and onunload

George picture George · Mar 28, 2012 · Viewed 52.4k times · Source

Consider the following HTML snippet containing some javascript utilizing prompt and unload. The prompt() method works fine but I want alerting something like Goodbye, user when reloading or leaving the page. Any help is greatly appreciated.

<body onload="promptName()" >


        <script type="text/javascript">
        function promptName()
        {
            var userName = prompt("What's your name ?", "")
            return userName;
        }

        function goodBye()
        {
            alert("Goodbye, " + promptName() + "!");
        }

        window.onunload = goodBye();

        </script>

  </body>

Answer

David Hellsing picture David Hellsing · Mar 28, 2012

You should write it like this:

window.onunload = goodBye;

Also, you might consider using the onbeforeunload event in some browsers:

window.onbeforeunload = goodBye;

When you write window.onunload = goodBye(); you assign whatever handler that is returned from goodBye to the unload event. Since nothing is returned, there will be no event handler. You need to reference the function instead: window.onunload = goodBye;