1

I'm using the following js to show a popup before the browser/window closes. But it does not seem to be working.

$(window).bind('beforeunload', function(e) {
    $('#beforeclose').click(); 
});

The popup i'm trying to show is prettyPopin . And the #beforeclose is the id of the anchor with which i'm trying to bind the click event before the window unloads. I have noticed that native js popups work but the jQuery popup does not work.

Is there a way to achieve what i want to? Please do explain to me or refer me to the respective link because i'm not an expert at js.

Thanks in advance.

xmaestro
  • 1,084
  • 2
  • 16
  • 44

3 Answers3

3

You cannot safely do that.

onbeforeunload is designed in a way to avoid completely preventing the user from leaving your page. The only thing you should do is return a string with a message why the user might not want to leave the page. This message is displayed to the user unless he's using firefox.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

Try this:

<script type="text/javascript">
        $(function() {
        function confirmmsg() {
            return "Mail Not sent";
        }
        window.onbeforeunload = confirmmsg;

        });
</script>
Vinod
  • 4,672
  • 4
  • 19
  • 26
0

Try changing it to

$(window).bind('beforeunload', function(e) {
    $('#beforeclose').click(); 
    e.preventDefault();
    return false; // just in case.. 
});

from jQuery documentation:

event.preventDefault()

Description: If this method is called, the default action of the event will not be triggered.

Basically, you are binding the function that shows the popup on the beforeunload event, but that does not block the browser like an alert window or something like that. Using event.preventDefault() you will stop the execution of event flow.

MilkyWayJoe
  • 9,082
  • 2
  • 38
  • 53
  • `beforeunload` doesn't work like this. You can only return a string that might (not firefox) or might not (firefox) be shown to the user in a prompt if he wants to leave the page or not. – ThiefMaster Apr 25 '12 at 06:16
  • Thanx man returning something stops the window from closing . but with a message telling me if i want to leave the page or no ... I don't want that message. I just want my jquery popup . Please do tell me if there is a way.. – xmaestro Apr 25 '12 at 06:18
  • See my answer. you cannot do that. – ThiefMaster Apr 25 '12 at 06:18
  • @ThiefMaster what other way is there or can we even achieve this? – xmaestro Apr 25 '12 at 06:24
  • I have writen that code on an assumption. Apparently it cannot be done: http://stackoverflow.com/questions/276660/how-can-i-override-the-onbeforeunload-dialog-and-replace-it-with-my-own – MilkyWayJoe Apr 25 '12 at 06:33