0

I have a page where a user can add some data. It' s not a form, but he/she must save it to keep it. I would like to add a function to warn them about not saved items if they click and other link leading to leaving the page.

I've tried this but it does not seem to work:

$(window).on('beforeunload', function(){
    if ($('.mustSave').is(':visible').length > 0) {
       // alert
    }
});

I use jQuery 2.1.1 and I'm afraid some of the code I tried is deprecated.

santa
  • 12,234
  • 49
  • 155
  • 255
  • possible duplicate of [Alert when browser window closed accidentally](http://stackoverflow.com/questions/1244535/alert-when-browser-window-closed-accidentally) – renakre May 11 '15 at 02:54
  • @erkaner They all show unload(), which has been deprecated since 1.8... – santa May 11 '15 at 02:56

2 Answers2

3

The only way you can alert at that point is to return a value. For example (jsfiddle):

addEventListener('beforeunload', function() {
    if (mycondition) return 'Do you really want to leave?';
});

Please note that it's annoying to the user, so only do it if it's absolutely crucial. It's a good idea to save intermediate data in localstorage or such so that closing the page wouldn't cause data loss.

bjb568
  • 11,089
  • 11
  • 50
  • 71
  • this is not a case where user will be annoyed if he is alerted of not saved items. What type of event listener will include closing a page? I guess I will also have to specify all links that will leave the page as well?.. – santa May 11 '15 at 03:02
  • @santa The event listener applies to window. – bjb568 May 11 '15 at 03:27
0

Pure JS way using beforeunload :

window.addEventListener("beforeunload", function (e) {

 var warningMessage = 'Unsaved changes present, if you leave the page your changes will be lost.';

    (e || window.event).returnValue = warningMessage;
    return warningMessage; 
});
Ankit
  • 1,471
  • 17
  • 29