Sukhjeevan
Sukhjeevan

Reputation: 3156

Jquery help needed for onbeforeunload event

I am using jquery onbeforeunload event in asp.net application. If i write event as given below then its working fine and display confirm dialog box.

var vGlobal = true;
var sMessage = "Leaving the page will lost in unsaved data!";

[ Working ]

> window.onbeforeunload = function() {
>   if (vGlobal == false) return
> sMessage; }

but its not working if i use bind method like as given below

[ Not working ]

$(window).bind("beforeunload", function(e) {
    if (vGlobal == false)
        return sMessage;
});

Anybody suggest me why its not working.Is there any difference between these two methods.

Code on aspx:

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

CLICK ON THIS LINK TO SEE RUNNING EXAMPLE

Upvotes: 2

Views: 5870

Answers (3)

Fenton
Fenton

Reputation: 250892

There is no benefit in using jQuery to bind the event to the window - all you are doing is adding the overhead of having jQuery parse the window into a jQuery object, which you aren't even using.

Therefore, using:

window.onbeforeunload = handler;

Is preferable to using jQuery to bind this event.

You can still perform the binding inside of the document ready section:

$(document).ready(function () {
    window.onbeforeunload = handler;
};

Upvotes: 0

Mutation Person
Mutation Person

Reputation: 30498

Apart from the fact that vGlobal is true and you are checking if (vGlobal == false), this smells like a $(document).ready() issue.

I.e. you should place the declaration inside a document.ready() handler as shown here:

$(document).ready(function(){
    $(window).bind("beforeunload", function(e) {
        if (vGlobal == false)
            return sMessage;
    });
});

Upvotes: 0

rahul
rahul

Reputation: 187030

See the updated version

You need to bind all the events inside document ready event.

Upvotes: 1

Related Questions