views:

58

answers:

2

I have a client that just got the Apple Magic Mouse. We built a recipe website and she get very upset when she is inputting all the information for the recipe, then goes for her new mouse and accidentally scrolls to the right and it will do a Back Browse and all her info is lost. So she wants to warning/pop up to prevent this from happening on that page.

Any suggestions or point me to some JS that does this?

Thanks.

+9  A: 

This is a basic 'warn before leave' script, when the contents of a textarea changes, the user will be notified if (s)he is about to leave the page:

<script type="text/javascript">
var changes = false;
window.onbeforeunload = function(){
   if(changes){
      return "You're about to leave this page.";
   }
};
</script>
<textarea onkeypress="window.changes=true">recipe here</textarea>
Lekensteyn
+1 this is how gmail etc. do it too.
Alec Smart
Yep, if there are brave harts who get hit by using this legacy code, WebKit (Google Chrome, Safari) does not support beforeunload with `addEventListener`.
Lekensteyn
The only reliable way is to set onbeforeunload as a property of window. Since there should be only one for each page, there's no reason why you'd want to use addEventListener anyway.
Juan Mendes
You gotta do something else than this for (for ex.) Opera. For links it is not so hard, but backbutton is un-fun to deal with I think.
npup
According to [this post](http://bytes.com/topic/javascript/insights/799229-browser-quirk-onload-onunload-do-not-fire-back-forward-refresh-opera), Opera does not need such a feature, as the state (including form values) is saved when the user leaves the page. Simply press 'Back' if you use Opera.
Lekensteyn
A: 

So she wants to warning/pop up to prevent this from happening on that page.

You can hook into the onBeforeUnload event of your browser and then show a confirmation message.

XIII