Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI Dialog OnBeforeUnload

I have a small problem. I'm attempting to catch the OnUnLoad Event of the Window and ask a confirmation question and if the user decides they want to stay then fine, and if they want to leave the page then they'll lose all unsaved data. Here's the issues...

I'm using a jQuery UI Dialog and when I put the following code on my page, I have the Dialog open, and when I click the back button on the browser, it never pops up the msgbox. It just refreshes the page:

<script type="text/javascript"> 
    $(window).bind('beforeunload', function() { 
            alert('you are an idiot!'); 
        } 
    );
</script>

And the solution that I'm using was a post here. Again, the msgbox will display fine if I do not have the jQuery UI Dialog open. If I do, then it doesn't display the msgbox and just refreshes the page.

Any ideas?

like image 475
clockwiseq Avatar asked Dec 11 '09 17:12

clockwiseq


4 Answers

The correct way to display the alert is to simply return a string. Don't call the alert() method yourself.

<script type="text/javascript">
    $(window).on('beforeunload', function() {
        if (iWantTo) {
            return 'you are an idiot!';
        }
    }); 
</script>

See also: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

like image 124
Jordan Ryan Moore Avatar answered Nov 11 '22 11:11

Jordan Ryan Moore


You can also make an exception for leaving the page via submitting a particular form:

$(window).bind('beforeunload', function(){
    return "Do you really want to leave now?";
});

$("#form_id").submit(function(){
    $(window).unbind("beforeunload");
});
like image 44
Tomáš Mleziva Avatar answered Nov 11 '22 10:11

Tomáš Mleziva


this works for me

$(window).bind('beforeunload', function() {
      return 'Do you really want to leave?' ;
});
like image 14
lndr Avatar answered Nov 11 '22 10:11

lndr


jQuery API specifically says not to bind to beforeunload, and instead should bind directly to the window.onbeforeunload, I just ran across a pretty bad memory in part due binding to beforeunload with jQuery.

like image 1
Thomas Avatar answered Nov 11 '22 10:11

Thomas