Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Unexpected behavior with onUnload() 1

Status
Not open for further replies.

Azathoth

Technical User
Jul 14, 2003
61
US
I have some javascript on my page that looks like this:

window.onunload=warn_form_data_loss();
form_dirty = true;

function warn_form_data_loss ()
{
if ( form_dirty = true)
{
var answer = (confirm("WARNING: You are about to navigate away from the current page, which may result in data loss. Would you like to proceed?"));
if (answer)
{alert("ok");}
else
window.stop;
}
}


For some reason, the onUnload() handler gets triggered when the page is loaded...anyone have any ideas as to why this is happening?
 
I don't know why that happens (it happens to me too), but it works the way you want if you just put the function call in the BODY tag's ONUNLOAD event.

Code:
<body onunload='warn_form_data_loss ()'>

Also, in the function, you have an if-conditional with a single-equals sign. FYI, you want to make sure this is '==' for what you want to do. I'll assume it was just a typo when you typed your post!

--Dave
 

It's calling the function because in your assignment, you have the "()" after the name, thus implying you wish to call it.

Do just this:

Code:
window.onunload=warn_form_data_loss;

And that should fix your problem.

Hope this helps,
Dan

 

Oh yes... and is "stop" a method that you're adding to the window object elsewhere? AFAIK, it isn't a default method (I'm assuming it's a method, even though you don't have () after it)?

Dan
 
Ah, the dreaded (). Thanks, BillyRay! I learned something new today!

--Dave
 
Yeah, that makes two of us...I had no idea about the () - thank you.

A final question: when the user clicks cancel in the confirm dialoge, I would obviously like the user to remain on the current page, and am not quite sure how to accomplish this.

window.stop();

Doesn't seem to be what I want. Anyone know?
 
Apparently window.stop() only works with Nutscrape. For any curious IE users:

document.execCommand('Stop');
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top